# TinyURL 的加密与解密
TinyURL是一种URL简化服务, 比如:当你输入一个URL https://leetcode.com/problems/design-tinyurl
时,它将返回一个简化的URL http://tinyurl.com/4e9iAk
.
要求:设计一个 TinyURL 的加密 encode
和解密 decode
的方法。你的加密和解密算法如何设计和运作是没有限制的,你只需要保证一个URL可以被加密成一个TinyURL,并且这个TinyURL可以用解密方法恢复成原本的URL。
以下错误的选项是?
## aop
### before
```cpp
#include
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 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 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 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 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)];
}
};
```