Leetcode—535. TinyURL 的加密与解密【中等】

2024每日刷题(110)

Leetcode---535. TinyURL 的加密与解密

实现代码

cpp 复制代码
class Solution {
public:

    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        while(!urlToCode.count(longUrl)) {
            string code;
            for(int i = 0; i < 6; i++) {
                code += alphabets[rand() % alphabets.size()];
            }
            if(!codeToUrl.count(code)) {
                urlToCode[longUrl] = code;
                codeToUrl[code] = longUrl;
                return "http://tinyurl.com/" + code;
            }
        }
        throw;
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl) {
        return codeToUrl[shortUrl.substr(19)];
    }
private:
    const string alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    unordered_map<string, string> urlToCode;
    unordered_map<string, string> codeToUrl;
};

// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));

运行结果


之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
插件开发12 分钟前
vs2015 cuda c++ 线程号的计算详解
开发语言·c++·算法
有点。13 分钟前
C++(前缀和与差分)
c++·算法
c++之路18 分钟前
Bazel C++ 构建系列文档(五):多目标与多包项目
java·开发语言·c++
Hello:CodeWorld23 分钟前
【C++ 避坑指南】告别缓冲区溢出!全面解析 std::snprintf 的安全美学与核心陷阱
开发语言·c++·安全
中云DDoS CC防护蔡蔡24 分钟前
游戏杀手- ACCN
运维·服务器·经验分享·网络安全·ddos
凡人叶枫24 分钟前
Effective C++ 条款38:通过复合塑模出 has-a 或 \“根据某物实现出\
linux·开发语言·c++·windows
凡人叶枫42 分钟前
Effective C++ 条款40:明智而审慎地使用多重继承
java·数据库·c++·嵌入式开发·effective c++
仍然.1 小时前
算法题目---BFS解决最短路问题
算法·宽度优先
ShineWinsu1 小时前
对于Linux:线程局部存储(TLS)和线程封装的解析
linux·c++·面试·线程·tls·线程封装·线程局部存储
工头阿乐1 小时前
使用Conan构建现代C++项目:完整指南
开发语言·c++