题目:

题解:
typedef struct {
int key;
char *val;
UT_hash_handle hh;
} HashItem;
HashItem *dataBase = NULL;
char* encode(char* longUrl) {
srand(time(0));
int key;
HashItem * pEntry = NULL;
while (true) {
key = rand();
pEntry = NULL;
HASH_FIND_INT(dataBase, &key, pEntry);
if (NULL == pEntry) {
break;
}
}
pEntry = (HashItem *)malloc(sizeof(HashItem));
pEntry->key = key;
pEntry->val = longUrl;
HASH_ADD_INT(dataBase, key, pEntry);
char *res = (char *)malloc(sizeof(char) * 64);
sprintf(res, "%s%d", "http://tinyurl.com/", key);
return res;
}
char* decode(char* shortUrl) {
char *p = shortUrl;
char *last = shortUrl;
while (last = strchr(p, '/')) {
p = last + 1;
}
int key = atoi(p);
HashItem * pEntry = NULL;
HASH_FIND_INT(dataBase, &key, pEntry);
if (NULL != pEntry) {
return pEntry->val;
}
return NULL;
}
2113

被折叠的 条评论
为什么被折叠?



