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

运行结果


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

相关推荐
特立独行的猫a12 分钟前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
Not Dr.Wang42216 分钟前
自动控制系统稳定性研究及判据分析
算法
VT.馒头17 分钟前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript
EnglishJun17 分钟前
数据结构的学习(四)---栈和队列
数据结构·学习
字节跳动的猫17 分钟前
2026四款AI 快速落地小项目
经验分享
ffqws_22 分钟前
A*算法:P5507 机关 题解
算法
YXXY31323 分钟前
模拟实现map和set
c++
阿猿收手吧!35 分钟前
【C++】引用类型全解析:左值、右值与万能引用
开发语言·c++
「QT(C++)开发工程师」39 分钟前
C++ 策略模式
开发语言·c++·策略模式
执着25943 分钟前
力扣hot100 - 108、将有序数组转换为二叉搜索树
算法·leetcode·职场和发展