My solution using hashlib....

  • 0
    import hashlib
    class Codec:
        def __init__(self):
            self.dic = dict()
        def encode(self, longUrl):
            """Encodes a URL to a shortened URL.
            :type longUrl: str
            :rtype: str
            shortUrl = longUrl
            if longUrl:
                hashv = hashlib.sha256(longUrl.encode()).hexdigest()[:7]
                while hashv in self.dic:
                    if self.dic[hashv] == logUrl:
                    hashv = hashlib.sha256(longUrl.encode()).hexdigest()[:7]
                self.dic[hashv] = longUrl
                shortUrl = '' + hashv 
                return shortUrl
        def decode(self, shortUrl):
            """Decodes a shortened URL to its original URL.
            :type shortUrl: str
            :rtype: str
            longUrl = shortUrl
            if shortUrl:
                hashv = shortUrl.split('/')[-1]
                if hashv in self.dic:
                    longUrl = self.dic[hashv]
            return longUrl
    # Your Codec object will be instantiated and called as such:
    # codec = Codec()
    # codec.decode(codec.encode(url))

Log in to reply

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