Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created February 28, 2018 14:42
Show Gist options
  • Save s4553711/ab17a29e3d2096e44e3372044ae42c57 to your computer and use it in GitHub Desktop.
Save s4553711/ab17a29e3d2096e44e3372044ae42c57 to your computer and use it in GitHub Desktop.
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));
@s4553711
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment