-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path535. Encode and Decode TinyURL.cpp
64 lines (43 loc) · 1.22 KB
/
535. Encode and Decode TinyURL.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
string convertbase62(long long sum) {
string ans = "";
while(sum) {
int rem = sum % 62;
char r;
if(rem >= 10 && rem <= 36) {
rem = rem - 10;
r = char(rem + int('a'));
} else if(rem >= 37 && rem<=61) {
rem = rem - 37;
r = char(rem + 'A');
} else {
r = rem + '0';
}
ans = ans + r;
sum = sum / 62;
}
return ans;
}
public:
unordered_map<string, string> m;
time_t timev;
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
long sum = 0;
for(auto c: longUrl)
sum = sum + int(c);
sum = sum % 256;
long long curtime = time(&timev);
sum = sum * curtime;
string shorturl = convertbase62(sum);
m[shorturl] = longUrl;
return shorturl;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
return m[shortUrl];
}
};
// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));