535_Encode and Decode TinyURL
Solution 1
class Codec:
import string
letters = string.ascii_letters + string.digits
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 dec == 0:
break
return ans
suffix = decto62(self.global_counter)
if self.full_tiny.get(longUrl) is None:
self.full_tiny[longUrl] = suffix
self.tiny_full[suffix] = longUrl
self.global_counter += 1
return "http://tinyurl.com/" + suffix
else:
return "http://tinyurl.com/" + full_tiny[longUrl]
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
idx = shortUrl.split('/')[-1]
if idx in self.tiny_full:
return self.tiny_full[idx]
else:
return None
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))Solution 2 固定6位数,随机取值
Last updated