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.
这一题还是比较有意思的,题目意思就是说输入一个网址,让你用算法缩短这个网址,而且能否复原原网址。
当然这一题可以耍点小聪明就过了,直接return longurl 和return shorturl返回原地址。不过这并非我们刷leetcode的本意。
下面上代码,我一会再解释代码的意思:
class Codec:
import string
letters = string.ascii_letters + string.digits #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
full_tiny = {}
tiny_full = {}
global_counter = 0
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
def decto62(dec):
ans = ""
while 1:
ans = self.letters[dec % 62] + ans
dec //= 62
if not dec:
break
print('ans:',ans)
return ans
suffix = decto62(self.global_counter)
if longUrl not in self.full_tiny:
self.full_tiny[longUrl] = suffix
self.tiny_full[suffix] = longUrl
self.global_counter += 1
return "http://tinyurl.com/" + suffix
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
idx = shortUrl.split('/')[-1]
print('fulltiny',self.full_tiny,self.tiny_full)
if idx in self.tiny_full:
return self.tiny_full[idx]
else:
return None
codec = Codec()
url='fffffffffff'
print(codec.decode(codec.encode(url)))
这里会输出以下内容:
ans: a
fulltiny {'fffffffffff': 'a'} {'a': 'fffffffffff'}
fffffffffff
解题思路:将输入的长地址与生成的短地址通过字典一一对应。dector62方法就是生成短地址的方法,通过global_counter的递增并取余,来获得短地址。