535.Encode and Decode TinyURL
class Solution {
private:
int size=6;
unordered_map<string,string> key1, key2;
char chr[62] = {'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
public:
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
if(key1.count(longUrl)) return key1[longUrl];
string shortUrl="https://tinyurl.com/";
srand(int(time(0)));
for(int i=0;i<size;i++)
shortUrl+=to_string(rand()%size);
key1[longUrl]=shortUrl;
key2[shortUrl]= longUrl;
return shortUrl;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
if(key2.count(shortUrl)) return key2[shortUrl] ;
return "" ;
}
};
// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));Last updated