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

运行结果


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

相关推荐
Go Work3 分钟前
npm 卡在 Step 7 七分钟,翻上去四行才看到 E404
经验分享·笔记
志起计算机编程4 分钟前
Clickhouse的几个关键优势
算法
重生之小比特8 分钟前
【算法拾光 7】双指针|两数之和 II - 输入有序数组 + 三数之和
算法
Hello World . .12 分钟前
【嵌入式学习笔记 Day 1】
linux·数据结构·笔记
小向是个Der13 分钟前
P02_你的变量住在哪里_教学文档
经验分享·笔记·stm32·单片机
H.莓飛17 分钟前
【数据结构】归并与外排序
linux·服务器·c语言·开发语言·数据结构·visual studio
文丑颜不良啊18 分钟前
LeetCode851~875题目解析
java·leetcode
Navigator_Z32 分钟前
LeetCode //C - 1304. Find N Unique Integers Sum up to Zero
c语言·算法·leetcode
Yyyyyy~41 分钟前
【C++】String
c++