TinyURL is a URL shortening service where you enter a URL such ashttps://leetcode.com/problems/design-tinyurland it returns a short URL such ashttp://tinyurl.com/4e9iAk.
Design theencodeanddecodemethods 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.
Solution 1
用26个小写字母+26个大写字母+10个数字 = 62个字符的方法给每位取值。
不固定短网址的长度,按顺序给短网址赋值
用两个Hash table 分别用来长网址转化成短网址,以及短网址转化为长网址。
classCodec:import string letters = string.ascii_letters + string.digits full_tiny ={} tiny_full ={} global_counter =0defencode(self,longUrl):"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str """defdecto62(dec): ans =""while1: ans = self.letters[dec %62]+ ans dec //=62if dec ==0:breakreturn ans suffix =decto62(self.global_counter)if self.full_tiny.get(longUrl)isNone: self.full_tiny[longUrl]= suffix self.tiny_full[suffix]= longUrl self.global_counter +=1return"http://tinyurl.com/"+ suffixelse:return"http://tinyurl.com/"+ full_tiny[longUrl]defdecode(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:returnNone# Your Codec object will be instantiated and called as such:# codec = Codec()# codec.decode(codec.encode(url))
classCodec:import stringimport random full_tiny ={} tiny_full ={} letters = string.ascii_letters + string.digitsdefencode(self,longUrl):"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str """defsix_addr(): ans='' tmp=''for i inrange(6): tmp=letters[random.randint(0,61)] ans=ans+tmpreturn ansif longUrl in full_tiny:return"http://tinyurl.com/"+ full_tiny[longUrl]else: suffix =six_addr() full_tiny[longUrl]=suffix tiny_full[suffix]= longUrlreturn"http://tinyurl.com/"+ suffix defdecode(self,shortUrl):"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str """ shortUrl = shortUrl.split('/')[-1]if shortUrl in tiny_full:return tiny_full[shortUrl]else:returnNone# Your Codec object will be instantiated and called as such:# codec = Codec()# codec.decode(codec.encode(url))