1,题目要求
将一个标准的URL转化为一个经过简化的URL地址。
2,题目思路
不懂这题的意思,经过百度之后了解到,就是将一个URL进行一定的映射,将其映射成某一个字符串,其中字符串由数字和字母组成的。
即:"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
从上面这个字符串中进行选取。
因此,整体的思路是定义两个map,以便进行相互的映射:
第一个map,将shortUrl与LongUrl相互对应;
第二个map,将longUrl与id相互对应。
3,程序源码
class Solution {
public:
string dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int id = 0;
unordered_map<string, string> en_m;
unordered_map<int, string> de_m;
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
if(en_m.find(longUrl) != en_m.end()) return en_m[longUrl];
id++;
int count = id;
string en_res = "";
while(count > 0)
{
en_res = dict[count%62] + en_res;
count = count/62;
}
while(en_res.size() < 6)
en_res = "0" + en_res;
en_m[longUrl] = en_res;
de_m[id] = longUrl;
return en_res;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
int id = 0;
for(int i = 0;i < shortUrl.size();i++)
id = id * 62 + (int)dict.find(shortUrl[i]);
if(de_m.find(id) != de_m.end()) return de_m[id];
return "";
}
};
// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));