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 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.
Approach #1: C++.
class Solution { public: // Encodes a URL to a shortened URL. string encode(string longUrl) { if (longToTiny.count(longUrl)) return baseUrl + longToTiny[longUrl]; string tinyString = ""; do { for (int i = 0; i < 6; ++i) { //srand((unsigned)time(0)); int index = rand() % characters.length(); tinyString += characters[index]; } } while (longToTiny.count(tinyString)); longToTiny[longUrl] = tinyString; tinyToLong[baseUrl+tinyString] = longUrl; return baseUrl + tinyString; } // Decodes a shortened URL to its original URL. string decode(string shortUrl) { return tinyToLong[shortUrl]; } private: string baseUrl = "http://www.leetcode.com/"; string characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; unordered_map<string, string> longToTiny; unordered_map<string, string> tinyToLong; }; // Your Solution object will be instantiated and called as such: // Solution solution; // solution.decode(solution.encode(url));
Approach #2: Python.
class Codec: alphabet = string.ascii_letters + ‘0123456789‘ def __init__(self): self.url2code = {} self.code2url = {} def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str """ while longUrl not in self.url2code: code = ‘‘.join(random.choice(Codec.alphabet) for _ in range(6)) if code not in self.code2url: self.code2url[code] = longUrl self.url2code[longUrl] = code return ‘http://tinyurl.com/‘ + self.url2code[longUrl] def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str """ return self.code2url[shortUrl[-6:]] # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url))
Time Submitted | Status | Runtime | Language |
---|---|---|---|
a few seconds ago | Accepted | 28 ms | python |
2 minutes ago | Accepted | 36 ms | python |
13 minutes ago | Accepted | 8 ms | cpp |
原文地址:https://www.cnblogs.com/ruruozhenhao/p/9982455.html
时间: 2024-10-06 11:20:23