▶ 要求给出一种对 URL 网址进行压缩和解压的算法,例如 https://leetcode.com/problems/design-tinyurl ←→ http://tinyurl.com/4e9iAk,在不允许打表的情况下应该无法压缩的。
● 代码,6 ms,完全不压缩,just for fun
class Solution
{
public:
// Encodes a URL to a shortened URL.
string encode(string longUrl) { return longUrl; }
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) { return shortUrl; }
};
class Solution
{
public:
string theLatestUrl;
string encode(string longUrl) { theLatestUrl = longUrl; return "whatever, doesn't matter"; }
string decode(string shortUrl) { return theLatestUrl; }
};
● 代码,9 ms,随机数打表法,加密之后的字符串只与原网址字符串在表中的存放位置有关,与其内容无关。类似的有各种打表法,需要依赖散列表来解码,时间复杂度 O(1),空间开销大。
class Solution
{
public:
unordered_map<string, string> um;
string encode(string longUrl)
{
const string baseUrl = "http://tinyurl.com/";
int r;
string ran;
srand();
for (r = rand() % , ran = to_string(r); um.count(baseUrl + ran) == ; r = rand() % , ran = to_string(r));
// 随机取一个空的位置把网址放进去
um[baseUrl + ran] = longUrl;
return baseUrl + ran;
}
string decode(string shortUrl)
{
if (um.count(shortUrl) == )
return um[shortUrl];
return "";
}
};