Problem description:

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.

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.

Solution:

  1. use two unordered_map to store the relation of original url and shorten url, shot2long and long2short.
  2. The whole process can be divided into 2 parts
    1. encode:
      • input would be original string
      • create a random 6 character string, which means we need to have a dictionary to search which character to use.
      • after created 6 character string, need to check whether if it’s already used.
    2. decode:
      • the input would be shorten url string
      • extract 6 character string from input, search whether it is stored in the map.
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
class Solution {
public:
Solution(){
dist= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
short2long.clear();
long2short.clear();
srand(time(NULL));
}

// Encodes a URL to a shortened URL.
string encode(string longUrl) {
string _return;
if(long2short.find(longUrl) != long2short.end())
_return = long2short[longUrl];
else{
int idx= 0;
string tmp="";
for(int i = 0; i< 6; i++){
tmp.push_back(dist[rand() % 62]);
}
cout<<tmp<<endl;
while(short2long.count(tmp)){
tmp[idx] = dist[rand() % 62];
idx = (idx +1 )%5;
}
short2long[tmp] = longUrl;
long2short[longUrl] = tmp;
_return = tmp;
}
//cout<< "http://tinyurl.com/"+_return<< endl;
return "http://tinyurl.com/"+_return;
}

// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
string _return;

_return = shortUrl.substr(shortUrl.find_last_of('/')+1);
_return = short2long.count(_return) ? short2long[_return]: shortUrl;
return _return;
}
private:
unordered_map<string, string> short2long, long2short;
string dist;
};

// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));