Maybe sha256 in python hashlib?


  • 0
    U

    I calculated the sha256 digest of longUrl and converted it into 62-ary number (a-z,A-Z,0-9), cut the last 6 digit and append it to the end of "http://tinyurl.com/"

    But for some reason python in leetcode has no access to hashlib so I used built-in hash() and the solution has been accepted also

    class Codec:
        def __init__(self):
            self.chartable = {i : str(i) for i in range(10)}  #0-9
            for i in range(10, 36):                           #A-Z
                self.chartable[i] = chr(55 + i)
            for i in range(36, 62):                           #a-z
                self.chartable[i] = chr(61 + i)
            self.urltable= {}
    
        def encode(self, longUrl):
            """Encodes a URL to a shortened URL.
            :type longUrl: str
            :rtype: str
            """
            #shadec = int(hashlib.sha256(longUrl.encode()).hexdigest(), 16)
            shadec = hash(longUrl)
            idx = []
            while len(idx) < 6:                                #last 6 digit
                shadec, digit = divmod(shadec, 62)
                idx.append(self.chartable[digit])
            urlkey = "".join(idx[::-1])
            self.urltable[urlkey] = longUrl
            return "http://tinyurl.com/" + urlkey
    
        def decode(self, shortUrl):
            """Decodes a shortened URL to its original URL.
            :type shortUrl: str
            :rtype: str
            """
            urlkey = shortUrl.split('/')[-1]
            return self.urltable[urlkey]
    

  • 0

    @ufjfeng said in Maybe sha256 in python hashlib?:

    python in leetcode has no access to hashlib

    I just tested it and it worked. You probably forgot to import hashlib.


Log in to reply
 

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