Python Base62 TinyURL Solution


  • 0
    B
    #base62 encoding
    def __init__(self):
        self.elems = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
        self.counter = 1
        self.map = {}
        self.mod = len(self.elems)
        self.short_url_len = 6
        self.encoded_urls = set()
        
    def encode(self, longUrl):
        
        """Encodes a URL to a shortened URL.
        
        :type longUrl: str
        :rtype: str
        e.g 100 in base 10 is 10^0 x 0 + 10^1 x 0 + 10^2 x 2 --> [1,0,0]
            100 in base 62 is 62^0 x 38 + 62^1 x 1 --> [1,38]
        
        """
        if longUrl in self.encoded_urls:
            return None
        
        short_url = ""
        counter_copy = self.counter
        power = len(str(counter_copy)) - 1
        while counter_copy > 0:
            digit = int(counter_copy / (self.mod ** power))
            counter_copy %= self.mod ** power
            print counter_copy,digit, power
            short_url += self.elems[digit] 
            power -= 1
    
        while len(short_url) < self.short_url_len:
            short_url = self.elems[0] + short_url
    
        self.map[self.counter] = longUrl
        self.counter += 1
        self.encoded_urls.add(longUrl)
        return "http://tiny.url/"+short_url
    
    def decode(self, shortUrl):
        """Decodes a shortened URL to its original URL.
        
        :type shortUrl: str
        :rtype: str
        """
        base_62_str = shortUrl[len("http://tiny.url/"):]
        power = len(base_62_str) -  1
        result = 0
        for character in base_62_str:
            digit = self.elems.rfind(character)
            result += self.mod ** power * digit
            power -= 1
         
        long_url = self.map[result]
        print long_url
        return long_url

Log in to reply
 

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