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 = 0; 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 > 0) { res = dict[count % 62] + res; count /= 62; } while (res.size() < 6) res = "0" + res; m[longUrl] = res; idm[id] = longUrl; return res; } // Decodes a shortened URL to its original URL. string decode(string shortUrl) { int id = 0; for (int i = 0; i < shortUrl.size();i++) { id = 62 * id + (int)(dict.find(shortUrl[i])); } if (idm.find(id) != idm.end())return idm[id]; return ""; }
参考: