2018年3月3日 星期六

[535] Encode and Decode TinyURL

寫的很卡的一題 囧
總覺得不知道哪裡怪怪的
真危險吶我吶
HAHAHA(笑著流淚)
還以為要對長網址做一些encode
結果原來不是 ?!
那和0~9, a~z, A~Z的 62個字元有什麼關係呢 ?___?
我只要用26個也是可以的是吧?! 囧 (就測資來說是可以的)
這世界真複雜啊~~~~~~(流淚again)

Encode and Decode TinyURL
/** Encodes a URL to a shortened URL. */
char maps[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static long db_id = 0;

struct _database{
    char *s;
}database[1024];

char* encode(char* longUrl) {
    long id = -1;
    int i;
    int len = strlen(longUrl);

    if (longUrl == NULL || len <1)
        return longUrl;

    for(i=0;i<db_id;i++)
        if(strcmp(database[i].s,longUrl)==0)
        {
            id = i;
            break;
        }

    if(id < 0)
    {
        database[db_id].s = malloc(sizeof(char)*(len+1));
        strncpy(database[db_id].s, longUrl, len);
        database[db_id].s[len] = '\0';
        id = db_id++;
    }  
   
    char *shortS = malloc(sizeof(char)*7);
    for(i=0;i<6;i++)
    {
        shortS[i] = maps[id%62];
        id/=62;
    }
    shortS[i] = '\0';
    return shortS;
}

/** Decodes a shortened URL to its original URL. */
char* decode(char* shortUrl) {
    int len = strlen(shortUrl);
    if (shortUrl == NULL || len < 1)
        return shortUrl;
    int id=0;
    for(int i=len-1; i>=0; i--)
    {
        int now =0;
        printf("now %c = %d\n", shortUrl[i], shortUrl[i]);

        if (shortUrl[i] >= 'a')
            now = 10 + shortUrl[i]-'a';
        else if (shortUrl[i] >= 'A')
            now = 10 + 26 + shortUrl[i]-'A';
        else
            now = shortUrl[i]-'0';
        id = id*62 + now;
    }
    return database[id].s;
}

// Your functions will be called as such:
// char* s = encode(s);
// decode(s);

沒有留言:

張貼留言