# 535.Encode and Decode TinyURL

**535.Encode and Decode TinyURL**

难度: Medium

> Note: This is a companion problem to the System Design problem: Design 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.

可以设计一个hashmap用来存储键值对，加密可以使用随机生成树。具体容量取决于size和用来加密的字符数。

```
class Solution {
private:
int size=6;
unordered_map<string,string> key1, key2;
 char chr[62] = {'0','1','2','3','4','5','6','7','8','9',
                  'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
                  'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

public:

    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        if(key1.count(longUrl)) return key1[longUrl];
        string shortUrl="https://tinyurl.com/";
        srand(int(time(0)));
        for(int i=0;i<size;i++)
        shortUrl+=to_string(rand()%size);
        key1[longUrl]=shortUrl;
        key2[shortUrl]= longUrl;
        return shortUrl;
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl) {
        if(key2.count(shortUrl)) return key2[shortUrl] ;
        return "" ;
    }
};

// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));
```

> 执行用时 :12 ms, 在所有 C++ 提交中击败了45.85%的用户\
> 内存消耗 :9.7 MB, 在所有 C++ 提交中击败了5.64%的用户
