LeetCode算法题535. Encode and Decode TinyURL
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.
题目的意思很简单就是要把一个例如 https://leetcode.com/problems/design-tinyurl 这样的长链接转化为 http://tinyurl.com/4e9iAk 这样的短链接,然后还能最后再转化回去。下面给出python3的解决方法:
- 定义两个函数encode()和decode(),模板已经有给出;
- 注意到短链接最后一共是有6个字符组成的字符串,由大小写字母和数字构成。这时候我们就可以使用python3中string库里提供的两个函数string.ascii_letters 和 string.digits生成a-z,A-Z,0~9的字符串.
- 创建两个字典,longtoshort用来从长URL映射到短URL,它的索引是longUrl,值为shortUrl 。 shorttolong相反。
longtoshort={}
shorttolong={} - 定义一个生成http://tinyurl.com/4e9iAk中4e9iAk这6个字符的函数
def key():
sixletters=''
t=''
for i in range(6):
t=letters[random.randint(0,10000)%62] #从a~z,A~Z,0~9中随机选一个字符,连续6次
sixletters+=t
return sixletters #返回6个随机字符
- 生成的6个字符拼接成短链接
if longUrl in longtoshort:
return 'http://tinyurl.com/'+longtoshort[longUrl]
else:
key=key()
longtoshort[longUrl]=key
shorttolong[key]=longUrl
return 'http://tinyurl.com/'+key
- 实现decode():只需要在shorttolong字典中查找,若存在就返回长链接。
def decode(self, shortUrl):
key=shortUrl.split('/')[-1]
if key in shorttolong:
return shorttolong[key]
- LeetCode运行结果和提交结果。