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

运行结果


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

相关推荐
无bug代码搬运工5 分钟前
LeetCode 42 接雨水:双指针解法详解
算法·leetcode·职场和发展
wuminyu10 分钟前
JUC包的AQS与JVM的ObjectMonitor机制对比分析
java·linux·c语言·jvm·c++
Jasmine_llq19 分钟前
《P13016 [GESP202506 六级] 最大因数》
数据结构·算法
就不掉头发28 分钟前
C++函数模板
java·开发语言·c++
白狐_79829 分钟前
考研408算法设计题保命策略:链表专题暴力解法精讲(2015 & 2019真题实战)
考研·算法·链表
努力的小雨1 小时前
ChinaJoy 排队一个半小时回来后,我用 Doubao-Seed-Evolving 写了一款抗战小游戏
经验分享·ai智能
fangpin1 小时前
GPU编程2: 并行策略
算法
蜜桃味女焊匠人1 小时前
焊接机器人对比人工焊接,工厂该怎么选?
人工智能·经验分享·其他·机器人
森诺Alyson1 小时前
前沿技术借鉴研讨-2026.8.6(影响中国育龄妇女生育偏好的因素/分孕周血压与不良妊娠结局的风险)
论文阅读·经验分享·学习·论文笔记
碧海银沙音频科技研究院1 小时前
8基于BES2700IHC数字助听器系统开发
嵌入式硬件·算法