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

运行结果


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

相关推荐
sali-tec3 小时前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
小明说Java3 小时前
常见排序算法的实现
数据结构·算法·排序算法
45288655上山打老虎3 小时前
C++完美转发
java·jvm·c++
行云流水20194 小时前
编程竞赛算法选择:理解时间复杂度提升解题效率
算法
SunkingYang4 小时前
程序崩溃闪退——MFC共享内存多次OpenFileMapping和MapViewOfFile而没有相应的UnmapViewOfFile和CloseHandle
c++·mfc·共享内存·崩溃·闪退·close·openfilemapping
问君能有几多愁~5 小时前
C++ 日志实现
java·前端·c++
smj2302_796826525 小时前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
JANGHIGH5 小时前
c++ 多线程(二)
开发语言·c++
珑墨5 小时前
【浏览器】页面加载原理详解
前端·javascript·c++·node.js·edge浏览器
cynicme5 小时前
力扣3531——统计被覆盖的建筑
算法·leetcode