535.Encode and Decode TinyURL

ss
Mar 16, 2021

--

這個就是在做短網址, 但要怎麼做呢

先準備兩個map, 分別是從長網址對應到短網址, 跟短網址對應回長網址

題目有提示可以做出六個random 的字母, 數字, 我們可以先列出所有字母數字, 然後分別用rand() % 62來製作

但假設rand所做出來的短網址已經被人用過了呢?

我們就在將這六個值一個一個改, 改到沒有人用過為止

最後decode即可直接查表找到長網址, 若查不到及回傳輸入的短網址即可

class Solution {
public:
Solution() {
dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
if (long2short.count(longUrl)) {
return "http://tinyurl.com/" + long2short[longUrl];
}
int index = 0;
string randStr;
for (int i = 0; i < 6; i++){
randStr.push_back(dict[rand() % 62]);
}
while (short2long.count(randStr)) {
randStr[index] = dict[rand() % 62];
index = (index + 1) % 5;
}
long2short[longUrl] = randStr;
short2long[randStr] = longUrl;
return "http://tinyurl.com/" + randStr;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
string randStr = shortUrl.substr(shortUrl.find_last_of("/") + 1);
return short2long.count(randStr) ? short2long[randStr] : shortUrl;
}
unordered_map<string, string> short2long, long2short;
string dict;
;
};

--

--

ss
ss

No responses yet