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));