Created
February 28, 2018 14:42
-
-
Save s4553711/ab17a29e3d2096e44e3372044ae42c57 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
Solution() { | |
for(string::size_type i = 0; i < chars.size(); i++) { | |
charToValueMap[chars[i]] = i; | |
} | |
} | |
// Encodes a URL to a shortened URL. | |
string encode(string longUrl) { | |
auto id = urls.size() + 1; | |
urls[id] = longUrl; | |
std::vector<char> digits; | |
while(id != 0) { | |
digits.emplace_back(chars[id%base]); | |
id /= base; | |
} | |
return baseUrl + string(digits.rbegin(), digits.rend()); | |
} | |
// Decodes a shortened URL to its original URL. | |
string decode(string shortUrl) { | |
auto idString = shortUrl.substr(baseUrlSize,shortUrl.size() - baseUrlSize); | |
auto id = NULL; | |
auto idStringSize = idString.size(); | |
for(string::size_type i = 0; i < idStringSize; i++) { | |
id += charToValueMap[idString[i]] * static_cast<uint64_t>(std::pow(base, idStringSize - i - 1)); | |
} | |
return urls[id]; | |
} | |
private: | |
const string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
const int base = chars.size(); | |
const string baseUrl = "http://tinyurl.com/"; | |
const int baseUrlSize= baseUrl.size(); | |
std::unordered_map<char, int> charToValueMap; | |
std::unordered_map<uint64_t, string> urls; | |
}; | |
// Your Solution object will be instantiated and called as such: | |
// Solution solution; | |
// solution.decode(solution.encode(url)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source: https://xenstalker.tw/2017/05/07/leetcode-problems-535-encode-and-decode-tinyurl/