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(C++)
class Solution {
private:
string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
unordered_map<char, string> map;
public:
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
char key = charset[rand() % charset.length()];
string encoded = "http://tinyurl.com/";
encoded += key;
map[key] = longUrl;
return encoded;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
//find key
char key = shortUrl[shortUrl.length()-1];
return map[key];
}
};
算法分析
略。
程序分析
这道题的背景还是很有意思的。可以参考: