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

运行结果


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

相关推荐
zander258几秒前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
程序喵大人4 分钟前
【C++进阶】STL容器与迭代器 - 10 把容器、迭代器和数据流串成一个小程序
开发语言·c++·容器·小程序·迭代器·stl
汤愈韬5 分钟前
模型求解算法
人工智能·算法·机器学习
Keven_1123 分钟前
算法札记:DP中的滚动数组
算法·滚动数组
luj_176825 分钟前
随机性在算法与占卜中的共通原理
c语言·开发语言·c++·经验分享·算法
-天涯7627 分钟前
桌面运维实战总结|Windows台式机10大类高频故障全套排查修复方案
经验分享·电脑·it·桌面运维·开机报错
Lazionr32 分钟前
vector初识——从动态数组到STL核心容器
开发语言·c++
yyds_yyd_1008637 分钟前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
Chen—LSN1 小时前
C语言——深度理解指针(5)
c语言·数据结构·算法·排序算法
呱呱巨基1 小时前
CMake基础
linux·c++·笔记·学习