之前去网易游戏面试,结果凉了。
当时面试官问了我一个问题:如何实现一个短网址(Tiny url)系统。当时我只说是建立一个映射,就跟哈希表的原理差不多。然后面试官问我用较短的网址去映射那么多的较长的网址,短网址够用吗?我当时理所当然地觉得:不够用,很快就否认了自己先前的想法。然后就慌了,接下来基本上啥也没说上来。。。
后来上网查这个问题的做法,发现LeetCode就有= =,而且其实思路大体也没错。
这是一种被称为base62的做法。只用6位的大小写字母加数字的组合来构造短网址,就可以有62^6(26个小写字母+26个大写字母+10个数字)种可能。这样就已经达到了五百亿的数量级,其实基本能够满足正常的短网址服务。
535. Encode
and Decode 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.
这是我的AC代码:
class Solution {
public:
unordered_map<string, int> ltos;
unordered_map<int, string> stol;
int COUNTER = 1;
string elements = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int base62ToBase10(string s) {
int n = 0;
for (int i = 0; i < s.length(); i++) {
n = n * 62 + convert(s[i]);
}
return n;
}
int convert(char c) {
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'z') {
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'Z') {
return c - 'A' + 36;
}
return -1;
}
string base10ToBase62(int n) {
string sb = "";
while (n != 0) {
sb=elements[n % 62]+sb;
n /= 62;
}
while (sb.length() != 6) {
sb='0'+sb;;
}
return sb;
}
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
string shorturl = base10ToBase62(COUNTER);
ltos[longUrl]=COUNTER;
stol[COUNTER]=longUrl;
COUNTER++;
return "http://tiny.url/" + shorturl;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
shortUrl = shortUrl.substr(17); //17 is the length of "http://tiny.url/"
int n = base62ToBase10(shortUrl);
return stol[n];
}
};
// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));