Encode and Decode TinyURL
这个题就是实现长网址变短网址的方法,实际上的做法和想象的用哈希函数是不一样的,我们不需要去基于长网址来生成短网址,而是可以按照九章课里面描述的纯随机生成六位码然后用哈希表(实际情况中就很像Cassandra这样的NoSQL数据库了)来存储对应关系即可,当然也可以用更复杂的Base62算法
class Codec:
charList = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
shortStore = {}
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
shortUrl = ''
for i in xrange(6):
shortUrl += random.choice(self.charList)
self.shortStore[shortUrl] = longUrl
return shortUrl
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
return self.shortStore[shortUrl]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))