[LeetCode] 535. Encode and Decode TinyURL 编码和解码短网址

时间:2022-05-06 20:49:49

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.

Python:

class Codec:
def __init__(self):
self.__random_length = 6
self.__tiny_url = "http://tinyurl.com/"
self.__alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
self.__lookup = {} def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str
:rtype: str
"""
def getRand():
rand = []
for _ in xrange(self.__random_length):
rand += self.__alphabet[random.randint(0, len(self.__alphabet)-1)]
return "".join(rand) key = getRand()
while key in self.__lookup:
key = getRand()
self.__lookup[key] = longUrl
return self.__tiny_url + key def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str
:rtype: str
"""
return self.__lookup[shortUrl[len(self.__tiny_url):]]

Python:Using sha256

from hashlib import sha256

class Codec:

    def __init__(self):
self._cache = {}
self.url = 'http://tinyurl.com/' def encode(self, long_url):
"""Encodes a URL to a shortened URL.
:type long_url: str
:rtype: str
"""
key = sha256(long_url.encode()).hexdigest()[:6]
self._cache[key] = long_url
return self.url + key def decode(self, short_url):
"""Decodes a shortened URL to its original URL.
:type short_url: str
:rtype: str
"""
key = short_url.replace(self.url, '')
return self._cache[key]

C++:

class Solution {
public:
Solution() : gen_((random_device())()) {
} // Encodes a URL to a shortened URL.
string encode(string longUrl) {
string key = getRand();
while (lookup_.count(key)) {
key = getRand();
}
lookup_[key] = longUrl;
return "http://tinyurl.com/" + key;
} // Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
return lookup_[shortUrl.substr(tiny_url.length())];
} private:
string getRand() {
string random;
for (int i = 0; i < random_length; ++i) {
random += alphabet_[uniform_int_distribution<int>{0, alphabet_.length() - 1}(gen_)];
}
return random;
} const int random_length = 6;
const string tiny_url = "http://tinyurl.com/";
const string alphabet_ = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
default_random_engine gen_;
unordered_map<string, string> lookup_;
};

  

类似题目:

[LeetCode] 534. Design TinyURL 设计短网址

All LeetCode Questions List 题目汇总