c_cpp 535.cpp
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 535.cpp相关的知识,希望对你有一定的参考价值。
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));
以上是关于c_cpp 535.cpp的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp 200.岛屿数量
c_cpp 127.单词阶梯
c_cpp MOFSET
c_cpp MOFSET
c_cpp 31.下一个排列
c_cpp string→char *