Using hash() function, python AC


  • 0
    D
    class Codec:
        urls = {}
        def encode(self, longUrl):
            genUrl = hash(longUrl)
            self.urls[genUrl]=longUrl
            return 'http://tinyurl.com/'+str(genUrl)
            """Encodes a URL to a shortened URL.
            
            :type longUrl: str
            :rtype: str
            """
            
    
        def decode(self, shortUrl):
            genUrl = long(shortUrl.split('/')[-1])
            return self.urls[genUrl]
    

    My solution is pretty straight forward. Generate a hash key using hash() for given longurl. Store the hashkey and longurl in the dictionary for decoding purpose. Append the hash to the tiny url and return it when encoding. For decoding,get the last word in the url and convert it to long/int to lookup in the url dict.


  • 1

    The URLs are fairly long, though, for example http://tinyurl.com/-4817917424256745919.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.