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
anddecode
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.
方法
提供一个map
和变量i
,每来一个url
的时候i++
,将url
和i
的对应关系存入map
即可
python代码
class Codec:
def __init__(self):
self.map = {}
self.i = 0
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
self.i += 1
self.map[self.i] = longUrl
return "http://tinyurl.com/" + str(self.i)
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
return self.map[int(shortUrl.split('/')[-1])]
# Your Codes object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
url = "https://leetcode.com/problems/design-tinyurl";
codec = Codec()
assert codec.decode(codec.encode(url)) == url
网友评论