要求
TinyURL是一种URL简化服务, 比如:当你输入一个URL leetcode.com/problems/de… 时,它将返回一个简化的URL tinyurl.com/4e9iAk.
要求:设计一个 TinyURL 的加密 encode 和解密 decode 的方法。你的加密和解密算法如何设计和运作是没有限制的,你只需要保证一个URL可以被加密成一个TinyURL,并且这个TinyURL可以用解密方法恢复成原本的URL。
核心代码
class Codec:
def __init__(self):
self.alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
self.s2l = dict()
self.l2s = dict()
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
while longUrl not in self.l2s:
code = "".join(random.choice(self.alpha) for _ in range(6))
if code not in self.s2l:
self.s2l[code] = longUrl
self.l2s[longUrl] = code
return "http://tinyurl.com/" + self.l2s[longUrl]
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
key = shortUrl[-6:]
return self.s2l[key]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
解题思路:其实就是构造一个数据结构,完成长短的加密和解密,我们使用random的方法随机的生成6位字母和数字的密码,然后生成两个字典用于存储原始url和加密的6位编码,用于加解密的过程,比较简单。