C语言 | Leetcode 题解之第535题TinyURL的加密与解密
题目:
题解:
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;
}