Comment on page

535.Encode and Decode TinyURL

535.Encode and Decode TinyURL
难度: Medium
Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL shortening service where you enter a URL such as and it returns a short URL such as
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
class Solution {
int size=6;
unordered_map<string,string> key1, key2;
char chr[62] = {'0','1','2','3','4','5','6','7','8','9',
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
if(key1.count(longUrl)) return key1[longUrl];
string shortUrl="";
for(int i=0;i<size;i++)
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));
执行用时 :12 ms, 在所有 C++ 提交中击败了45.85%的用户 内存消耗 :9.7 MB, 在所有 C++ 提交中击败了5.64%的用户