> For the complete documentation index, see [llms.txt](https://lei-d.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lei-d.gitbook.io/leetcode/hash-table/535encode-and-decode-tinyurl.md).

# 535\_Encode and Decode TinyURL

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.

## Solution 1

用26个小写字母+26个大写字母+10个数字 = 62个字符的方法给每位取值。

不固定短网址的长度，按顺序给短网址赋值

用两个Hash table 分别用来长网址转化成短网址，以及短网址转化为长网址。

```python
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 dec == 0:
                    break
            return ans

        suffix = decto62(self.global_counter)
        if self.full_tiny.get(longUrl) is None:
            self.full_tiny[longUrl] = suffix
            self.tiny_full[suffix] = longUrl
            self.global_counter += 1
            return "http://tinyurl.com/" + suffix
        else:
            return "http://tinyurl.com/" + full_tiny[longUrl]



    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]
        else:
            return None


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

## Solution 2 固定6位数，随机取值

这是一种被称为base62的做法。只用6位的大小写字母加数字的组合来构造短网址，就可以有62^6（26个小写字母+26个大写字母+10个数字）种可能。这样就已经达到了五百亿的数量级，其实基本能够满足正常的短网址服务。

```python
class Codec:
    import string
    import random
    full_tiny = {}
    tiny_full = {}
    letters = string.ascii_letters + string.digits

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

        :type longUrl: str
        :rtype: str
        """
        def six_addr():
            ans=''
            tmp=''
            for i in range(6):
                tmp=letters[random.randint(0,61)]
                ans=ans+tmp
            return ans
        if longUrl in full_tiny:
            return "http://tinyurl.com/" + full_tiny[longUrl]
        else:
            suffix = six_addr()
            full_tiny[longUrl]=suffix
            tiny_full[suffix] = longUrl
            return "http://tinyurl.com/" + suffix 

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

        :type shortUrl: str
        :rtype: str
        """
        shortUrl = shortUrl.split('/')[-1]
        if shortUrl in tiny_full:
            return tiny_full[shortUrl]
        else:
            return None

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