题目描述
思路
哈希表
根据题意,主要考察的是使用哈希表存储原url和新url的键值对关系,至于加密解密使用什么算法并没有要求。
Python实现
K1, K2 = 1117, 10**9+7
class Codec:
def __init__(self):
self.map = {}
self.urlToKey = {}
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
if longUrl in self.urlToKey:
return "http://tinyurl.com/" + str(self.urlToKey[longUrl])
key, base = 0, 1
for ch in longUrl:
key = (key + ord(ch) * base) % K2
base = (base * K1) % K2
while key in self.map:
key = (key+1) % K2
self.map[key] = longUrl
self.urlToKey[longUrl] = key
return "http://tinyurl.com/" + str(key)
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
i = shortUrl.rfind('/')
key = int(shortUrl[i+1:])
return self.map[key]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
Java实现
public class Codec {
static final int K1 = 1117;
static final int K2 = 1000000007;
private Map<Integer, String> dataBase = new HashMap<Integer, String>();
private Map<String, Integer> urlToKey = new HashMap<String, Integer>();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
if (urlToKey.containsKey(longUrl)) {
return "http://tinyurl.com/" + urlToKey.get(longUrl);
}
int key = 0;
long base = 1;
for (int i = 0; i < longUrl.length(); i++) {
char ch = longUrl.charAt(i);
key = (int) ((key + (long) ch * base) % K2);
base = (base * K1) % K2;
}
while (dataBase.containsKey(key)) {
key = (key + 1) % K2;
}
dataBase.put(key, longUrl);
urlToKey.put(longUrl, key);
return "http://tinyurl.com/" + key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
int i = shortUrl.lastIndexOf("/") + 1;
int key = Integer.parseInt(shortUrl.substring(i));
return dataBase.get(key);
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
C++实现
const long long K1 = 1117;
const long long K2 = 1e9+7;
class Solution {
private:
unordered_map<int, string> dataBase;
unordered_map<string, int> urlToKey;
public:
Solution() {
}
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
if (urlToKey.count(longUrl) > 0) {
return string("http://tinyurl.com/") + to_string(urlToKey[longUrl]);
}
long long key = 0, base = 1;
for (auto c : longUrl) {
key = (key + c * base) % K2;
base = (base * K1) % K2;
}
while (dataBase.count(key) > 0) {
key = (key + 1) % K2;
}
dataBase[key] = longUrl;
urlToKey[longUrl] = key;
return string("http://tinyurl.com/") + to_string(key);
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
int i = shortUrl.rfind('/')+1;
int key = stoi(shortUrl.substr(i, int(shortUrl.size()) - i));
return dataBase[key];
}
};
// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));