Open Zheaoli opened 2 years ago
//随机hash实现
Map<String, String> db = new HashMap<>();
Map<String, String> cache = new HashMap<>();
Random rd = new Random();
final int k = 6;
final String base = "http://tinyurl.com/";
final char[] dict = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
if (cache.containsKey(longUrl))
return base + cache.get(longUrl);
String shortUrl;
do {
char[] chs = new char[k];
for (int i = 0; i < k; i++) {
chs[i] = dict[rd.nextInt(dict.length)];
}
shortUrl = new String(chs);
} while(db.containsKey(shortUrl));
db.put(shortUrl, longUrl);
cache.put(longUrl, shortUrl);
return base + shortUrl;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return db.get(shortUrl.substring(shortUrl.lastIndexOf("/") + 1));
}
}
WeChat: Saraad
#include <iostream>
#include <unordered_map>
using namespace std;
/*
* @lc app=leetcode.cn id=535 lang=cpp
*
* [535] TinyURL 的加密与解密
*/
// @lc code=start
class Solution
{
private:
unordered_map<int, string> data;
int max_id = 0;
public:
// Encodes a URL to a shortened URL.
string encode(string longUrl)
{
max_id++;
data[max_id] = longUrl;
return "http://tinyurl.com/" + to_string(max_id);
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl)
{
string data_id = shortUrl;
size_t pos;
string delimiter = "/";
while ((pos = data_id.find(delimiter)) != string::npos)
{
data_id.erase(0, pos + delimiter.length());
}
return data[std::stoi(data_id)];
}
};
// @lc code=end
int main()
{
string url = "https://leetcode.com/problems/design-tinyurl";
Solution solution;
return url != solution.decode(solution.encode(url));
}
微信id: 而我撑伞 来自 vscode 插件
2022-06-29