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

运行结果


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

相关推荐
OPEN-F7 分钟前
ROS2系列教程:Gazebo插件(关节控制/IMU/激光雷达)
c++·python·数码相机·算法·机器人
luj_176814 分钟前
虚实交融中的真实人物塑造
c语言·开发语言·网络·经验分享·算法
蒸蒸yyyyzwd20 分钟前
cpp 选手秋招学习笔记 day27
服务器·c++·面试·八股
裕晟专利申请刘老师37 分钟前
无锡知识产权保护中心预审怎么走,发明专利40天授权怎么做到
经验分享
haolin123.44 分钟前
STL vector底层揭秘:从构造到迭代器失效
开发语言·c++·算法
尘中远1 小时前
给C++工业软件搭建 Agent
开发语言·c++·qt·ai·agent
shehuiyuelaiyuehao1 小时前
算法37,位运算,两个整数之和(不用+符号)
算法
2401_868534781 小时前
网规备考_2.4 路由协议
c++·设计模式
猎头南楼1 小时前
MFC 质量流量控制器中的控制算法设计与落地思考
人工智能·算法
来一碗刘肉面1 小时前
平衡二叉树的删除
数据结构·算法