Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
encode-and-decode-tinyurl.cpp 1.13 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-03-19 18:20 +08:00 . Create encode-and-decode-tinyurl.cpp
// Time: O(1)
// Space: O(n)
class Solution {
public:
Solution() : gen_((random_device())()) {
}
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
string key = getRand();
while (lookup_.count(key)) {
key = getRand();
}
lookup_[key] = longUrl;
return "http://tinyurl.com/" + key;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
return lookup_[shortUrl.substr(tiny_url.length())];
}
private:
string getRand() {
string random;
for (int i = 0; i < random_length; ++i) {
random += alphabet_[uniform_int_distribution<int>{0, alphabet_.length() - 1}(gen_)];
}
return random;
}
const int random_length = 6;
const string tiny_url = "http://tinyurl.com/";
const string alphabet_ = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
default_random_engine gen_;
unordered_map<string, string> lookup_;
};
// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助