这是关于编解码的问题。没有什么好的思路,除了com可以缩写。
看了一下,它用字典
参考了这个解题方法
class Codec:
def __init__(self):
self.long2short = {}
self.short2long = {}
self.alphabet = string.ascii_letters + '0123456789'
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
while longUrl not in self.long2short:
short = ''.join(random.choice(self.alphabet) for _ in range(6))
if short not in self.short2long:
self.long2short[longUrl] = short
self.short2long[short] = longUrl
return 'http://tinyurl.com/'+self.long2short[longUrl]
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return self.short2long[shortUrl[-6:]]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))