PU Encode and Decode TinyURL

Jan 01, 1970

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.

Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

Python Solution 1:

class Codec:

    def __init__(self):
        self.d = {}
        self.l = {}


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

        :type longUrl: str
        :rtype: str
        """
        if longUrl in self.l: 
            return self.l[longUrl]
        while True:
            random_string = "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
            if random_string not in self.d: 
                self.d[random_string] = longUrl
                self.l[longUrl] = random_string
                break
        return random_string


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

        :type shortUrl: str
        :rtype: str
        """
        return self.d[shortUrl]


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

Python Solution 2:

class Codec:
    chars = string.ascii_letters + string.digits

    def __init__(self):
        self.codetourl = {}

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

        :type longUrl: str
        :rtype: str
        """
        while True:
            code = ''.join(random.choice(Codec.chars) for _ in range(6))
            if code not in self.codetourl: break
        self.codetourl[code] = longUrl
        return 'http://tinyurl.com/' + code

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

        :type shortUrl: str
        :rtype: str
        """
        code = shortUrl.split('/')[-1]
        return self.codetourl.get(code, "")

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

Summary:

  • https://discuss.leetcode.com/topic/81637/two-solutions-and-thoughts
  • He's really clever.

LeetCode: 535. Encode and Decode TinyURL