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

运行结果


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

相关推荐
Jasmine_llq6 分钟前
《P15798 [GESP202603 五级] 有限不循环小数》
算法·有限小数判定数论定理·质因子约分检验·枚举生成合法数字·哈希集合去重·快速 io 优化
学计算机的计算基14 分钟前
操作系统八股文:进程与线程全面梳理(附调度算法+IPC+锁机制)
java·算法
Mortalbreeze15 分钟前
深入理解 Linux 线程机制(四):线程同步——条件变量与信号量
linux·运维·服务器·开发语言·c++
天竺鼠不该去劝架1 小时前
金融智能体如何对接老旧核心系统?不改造、全审计、数据不出域落地方案
经验分享
程序猿乐锅1 小时前
【数据结构与算法 | 第二篇】 双链表的增删改查
数据结构
xyy1231 小时前
C# Polly 弹性策略库指南
算法
郝学胜-神的一滴1 小时前
中级OpenGL教程 020:巧用数组与循环实现多点点光源渲染,告别冗余代码重构方案
c++·unity·游戏引擎·godot·图形渲染·unreal
zmzb01031 小时前
C++课后习题训练记录Day160
开发语言·c++
沫璃染墨2 小时前
现代C++⊂C++11篇(一)列表初始化全解 & std::initializer_list
开发语言·c++
阿米亚波2 小时前
【C++ STL】std::forward_list
开发语言·c++·笔记·stl·visual studio·forward_list