Leetcode 535 Solution

This article provides solution to leetcode question 535 (encode-and-decode-tinyurl)

https://leetcode.com/problems/encode-and-decode-tinyurl

Solution

class Codec:
    def __init__(self):
        self.alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        self.m = {}

    def encode(self, longUrl):
        """Encodes a URL to a shortened URL.

        :type longUrl: str
        :rtype: str
        """
        while True:
            key = ""
            for i in range(6):
                key += self.alphabet[random.randint(0, len(self.alphabet) - 1)]
            if key not in self.m:
                break
        self.m[key] = longUrl
        return "http://tinyurl.com/{}".format(key)


    def decode(self, shortUrl):
        """Decodes a shortened URL to its original URL.

        :type shortUrl: str
        :rtype: str
        """
        key = shortUrl[19:]
        return self.m[key]

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))