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

运行结果


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

相关推荐
Js.Tx3 小时前
【具体数学 Concrete Mathematics】2.1.5 一般性的方法
算法·具体数学
Risehuxyc4 小时前
C++(VS2026)使用Ncap库的配置
c++
秋天的怀念_David4 小时前
算法一千零一夜 · 作品相关:版权与致谢声明
程序人生·算法·学习方法
图灵-M4 小时前
【数据结构】静态 & 动态顺序表
c语言·数据结构·笔记
4ever.ov05 小时前
精学C++第一站 从命名空间到引用:C++入门核心语法全梳理(13000字长文)
开发语言·c++·clion
揽星河..5 小时前
【C语言】数组
c语言·开发语言·算法
careathers5 小时前
【数据结构】基于比较的排序算法 - 选择排序
数据结构·算法·排序算法
听风若依5 小时前
C++模板初阶
c++·算法
纪念 2296 小时前
C++ 算法(模拟)
开发语言·c++·算法
揽星河..6 小时前
【C语言】函数
c语言·算法