Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit8285e01

Browse files
authored
Merge pull requestneetcode-gh#2198 from seinlin/535
Add 0535-encode-and-decode-tinyurl.c
2 parents8f71f5a +b709244 commit8285e01

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎c/0535-encode-and-decode-tinyurl.c

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Represent an element in a hash table.
2+
typedefstructHash {
3+
char*key;
4+
char*value;
5+
UT_hash_handlehh;
6+
}Hash;
7+
8+
Hash*root=NULL;
9+
10+
char*UrlToKey(char*url) {
11+
char*key=NULL;
12+
unsignedinthash=1853;
13+
inti=0;
14+
15+
while (i<strlen(url)) {
16+
hash= ((hash <<5)+hash)+url[i];
17+
i++;
18+
}
19+
20+
key= (char*)calloc(32,1);
21+
snprintf(key,32,"http://tinyurl.com/%X",hash);
22+
returnkey;
23+
}
24+
25+
/** Encodes a URL to a shortened URL. */
26+
char*encode(char*longUrl) {
27+
Hash*entry=NULL;
28+
char*key=NULL;
29+
key=UrlToKey(longUrl);
30+
HASH_FIND_STR(root,key,entry);
31+
if (!entry) {
32+
entry=malloc(sizeof(Hash));
33+
entry->key=key;
34+
entry->value=longUrl;
35+
HASH_ADD_KEYPTR(hh,root,key,strlen(key),entry);
36+
}else {
37+
free(key);
38+
}
39+
returnentry->key;
40+
}
41+
42+
/** Decodes a shortened URL to its original URL. */
43+
char*decode(char*shortUrl) {
44+
Hash*entry=NULL;
45+
HASH_FIND_STR(root,shortUrl,entry);
46+
if (entry) {
47+
returnentry->value;
48+
}
49+
returnNULL;
50+
}
51+
52+
// Your functions will be called as such:
53+
// char* s = encode(s);
54+
// decode(s);
55+

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp