Encode and Decode TinyURL
Encode and Decode TinyURL
class Solution {
private:
string s;
unordered_map<string, string> HashMap;
public:
Solution() {
HashMap = {};
for (int i = 0 ; i < 26 ; ++i) {
if (i < 10) s += ('0' + i);
s += string(1, 'a' + i) + string(1, 'A' + i);
}
}
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
string ans;
for (int i = 0 ; i < 6 ; ++i) {
ans += s[rand() % s.size()];
}
HashMap[ans] = longUrl;
return ans;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
return HashMap[shortUrl];
}
};