# TinyURL 的加密与解密

<p>TinyURL是一种URL简化服务， 比如：当你输入一个URL&nbsp;<code>https://leetcode.com/problems/design-tinyurl</code>&nbsp;时，它将返回一个简化的URL&nbsp;<code>http://tinyurl.com/4e9iAk</code>.</p>

<p>要求：设计一个 TinyURL 的加密&nbsp;<code>encode</code>&nbsp;和解密&nbsp;<code>decode</code>&nbsp;的方法。你的加密和解密算法如何设计和运作是没有限制的，你只需要保证一个URL可以被加密成一个TinyURL，并且这个TinyURL可以用解密方法恢复成原本的URL。</p>

<p>以下错误的选项是？</p>

## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));
```

## 答案
```cpp
class Solution
{
public:
    map<string, string> mp;

    string encode(string longUrl)
    {
        string str = "tinyurl" + to_string(key);
        mp[str] = longUrl;
        return str;
    }

    string decode(string shortUrl)
    {
        return mp[shortUrl];
    }
};
```
## 选项

### A
```cpp
class Solution
{
public:
    unordered_map<string, string> hashMap;
    string TINYURL_PREFIX = "http://tinyurl.com/";
    string INDEX = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    string encode(string longUrl)
    {
        string newShortStr = "";
        while (true)
        {

            for (int i = 0; i < 6; ++i)
            {
                newShortStr += INDEX[rand() % 62];
            }

            string resStr = TINYURL_PREFIX + newShortStr;
            if (hashMap.count(resStr) == 0)
            {
                hashMap[resStr] = longUrl;
                return resStr;
            }
        }
    }
    string decode(string shortUrl)
    {
        return hashMap[shortUrl];
    }
};
```

### B
```cpp
class Solution
{
public:
    using ull = unsigned long long;
    const ull base = 11;
    const string code = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const ull len = code.size();
    unordered_map<string, string> m;

    ull hashCode(string url)
    {
        ull hash = 0;
        for (auto c : url)
        {
            hash *= base;
            hash += c;
        }
        return hash;
    }
    string hashToString(ull n)
    {
        string ans;
        while (n)
        {
            ans += code[n % len];
            n /= len;
        }
        return ans;
    }

    string encode(string longUrl)
    {
        string shortUrl = hashToString(hashCode(longUrl));
        m[shortUrl] = longUrl;
        return shortUrl;
    }

    string decode(string shortUrl)
    {
        return m[shortUrl];
    }
};
```

### C
```cpp
class Solution
{
public:
    unordered_map<string, string> mp;
    int i = 0;
    string encode(string longUrl)
    {
        mp[to_string(i)] = longUrl;
        string res = "http://tinyurl.com/" + to_string(i++);
        return res;
    }
    string decode(string shortUrl)
    {
        return mp[shortUrl.substr(19, shortUrl.size() - 19)];
    }
};
```
