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.
思路:
encode : 将网址映射到一个id上,使用hash map,保存对应的id和网址。
decode:用短网址计算出id,然后返回对应的长网址。
string dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int id = ;
unordered_map<string, string>m;
unordered_map<int, string>idm;
// Encodes a URL to a shortened URL.
string encode(string longUrl)
{
if (m.find(longUrl) != m.end())return m[longUrl];
string res = "";
id++;
int count = id;
while (count > )
{
res = dict[count % ] + res;
count /= ;
}
while (res.size() < ) res = "" + res;
m[longUrl] = res;
idm[id] = longUrl;
return res;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl)
{
int id = ;
for (int i = ; i < shortUrl.size();i++)
{
id = * id + (int)(dict.find(shortUrl[i]));
}
if (idm.find(id) != idm.end())return idm[id];
return "";
}
参考: