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

运行结果


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

相关推荐
MegaDataFlowers10 分钟前
102.二叉树的层序遍历
数据结构
洛水水10 分钟前
【力扣100题】28. 翻转二叉树
算法·leetcode
雪度娃娃14 分钟前
结构型设计模式——外观模式
c++·设计模式·外观模式
故事和你9119 分钟前
洛谷-【数据结构2-2】线段树2
开发语言·数据结构·算法·动态规划·图论
ghie909021 分钟前
MATLAB 随机蛙跳算法 (SFLA) 优化最小二乘回归
算法·matlab·回归
wuweijianlove22 分钟前
算法优化中的缓存层次结构与内存映射的技术7
算法
故事和你9124 分钟前
洛谷-【数据结构2-2】线段树1
开发语言·javascript·数据结构·算法·动态规划·图论
蜡笔小马25 分钟前
05.C++设计模式-适配器模式
c++·设计模式·适配器模式
code_pgf28 分钟前
Python `asyncio` 与 C++ Fiber 的原理与逻辑分析
c++·人工智能·python
电科一班林耿超29 分钟前
机器学习大师课 第 8 课:端到端项目实战 —— 泰坦尼克号生存预测
人工智能·算法·机器学习