[Leetcode] 535. Encode and Decode TinyURL 解题报告

本文介绍了一种URL缩短服务的设计方案,通过将长链接转换为短链接并保持可逆性。利用十进制ID到六十二进制字符串的转换方法,确保每个长链接都能被唯一地映射为短链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Note: This is a companion problem to the  System Design problem:  Design TinyURL.

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.

Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

思路

目测这道题目应该有多种不同的解法,这里给出其中的一种。维护一个全局的id,每次遇到新的longUrl,就给它赋一个新的id。现在问题就是如何把id映射为一个shortUrl了。我们采用的做法是:把这个shortUrl看作是一个“62进制”的数,其基由10个数字加上26个小写字母以及26个大写字母组成。这样问题就转化为10进制的id和62进制的shortUrl了(用string表示)之间的转换了。

encode:遇到一个新的longUrl后,我们赋给它一个新的id,然后将这个10进制的id转换为62进制的shortUrl,并且建立longUrl到shortUrl之间的哈希映射,以及id到longUrl之间的映射,以便于decode的时候使用。

decode:遇到一个shortUrl之后,我们将它转换为10进制的id,然后在哈希表中查找,返回对应的longUrl即可。

当然也可以直接建立shortUrl到longUrl之间的映射,而不是id到longUrl之间的映射。这样在decode的时候,就不需要进行进制之间的转换了。读者可以试着实现一下。

代码

class Solution {
public:

    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        if(long_short.find(longUrl) != long_short.end()) {
            return long_short[longUrl];
        }
        string res = "";
        id++;
        int count = id;
        while(count > 0) {
            res = dict[count % 62] + res;
            count /= 62;
        }
        while(res.size() < 6) {
            res = "0" + res;
        }
        long_short[longUrl] = res;
        id_long[id] = longUrl;
        return res;
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl) {
        int id = 0;
        for(int i = 0; i < shortUrl.size(); i++) {
            id = 62 * id + (int)(dict.find(shortUrl[i]));
        }
        if(id_long.find(id) != id_long.end()) {
            return id_long[id];
        }
        return "";
    }
private:
    string dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int id = 0;
    unordered_map<string,string> long_short;    // key is longURL, value is shortURL
    unordered_map<int, string> id_long;         // key is id in DB, value is longURL
};

// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值