Easy to Understand in Python

  • 4

    The main idea is to increase the global index, and transform the index into 26 * 2 + 10 based number in string format.
    And I used 2-way dictionary to simulate database queries on backend.

    class Codec:
        import string
        letters = string.ascii_letters + string.digits
        full_tiny = {}
        tiny_full = {}
        global_counter = 0
        def encode(self, longUrl):
            """Encodes a URL to a shortened URL.
            :type longUrl: str
            :rtype: str
            def decto62(dec):
                ans = ""
                while 1:
                    ans = self.letters[dec % 62] + ans
                    dec //= 62
                    if not dec:
                return ans
            suffix = decto62(self.global_counter)
            if longUrl not in self.full_tiny:
                self.full_tiny[longUrl] = suffix
                self.tiny_full[suffix] = longUrl
                self.global_counter += 1
            return "http://tinyurl.com/" + suffix
        def decode(self, shortUrl):
            """Decodes a shortened URL to its original URL.
            :type shortUrl: str
            :rtype: str
            idx = shortUrl.split('/')[-1]
            if idx in self.tiny_full:
                return self.tiny_full[idx]
                return None```

Log in to reply

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