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和用来加密的字符数。
1
class Solution {
2
private:
3
int size=6;
4
unordered_map<string,string> key1, key2;
5
char chr[62] = {'0','1','2','3','4','5','6','7','8','9',
6
'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',
7
'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'};
8
9
public:
10
11
// Encodes a URL to a shortened URL.
12
string encode(string longUrl) {
13
if(key1.count(longUrl)) return key1[longUrl];
14
string shortUrl="https://tinyurl.com/";
15
srand(int(time(0)));
16
for(int i=0;i<size;i++)
17
shortUrl+=to_string(rand()%size);
18
key1[longUrl]=shortUrl;
19
key2[shortUrl]= longUrl;
20
return shortUrl;
21
}
22
23
// Decodes a shortened URL to its original URL.
24
string decode(string shortUrl) {
25
if(key2.count(shortUrl)) return key2[shortUrl] ;
26
return "" ;
27
}
28
};
29
30
// Your Solution object will be instantiated and called as such:
31
// Solution solution;
32
// solution.decode(solution.encode(url));
Copied!
执行用时 :12 ms, 在所有 C++ 提交中击败了45.85%的用户 内存消耗 :9.7 MB, 在所有 C++ 提交中击败了5.64%的用户
Copy link