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

运行结果


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

相关推荐
电科_银尘8 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
我不会插花弄玉10 小时前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴11 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David11 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
西西弗Sisyphus12 小时前
C++ explicit 关键字工程实践
开发语言·c++
LK_0714 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi14 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK15 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
神明不懂浪漫15 小时前
【第八章】多线程(一)
java·开发语言·经验分享·笔记
文丑颜不良啊15 小时前
LeetCode3341~3360题目解析
java·leetcode