535. Encode and Decode TinyURL(python+cpp)

本文介绍了一个TinyURL服务的设计方案,该服务可以将长网址转换为短网址,并能将其还原回原始网址。通过使用字典存储长网址和短网址的对应关系,确保了短网址的唯一性和可逆性。

摘要生成于 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.

解释:
用字典保存shortUrl所对应的 longUrl,shortUrl需要有唯一的标识。
python代码:

class Codec:
    def __init__(self):
        self._dict={}
        self.key=0

    def encode(self, longUrl):
        """Encodes a URL to a shortened URL.
        
        :type longUrl: str
        :rtype: str
        """
        txt="tinyurl"+str(self.key)
        self._dict[txt]=longUrl
        self.key+=1
        return txt
        

    def decode(self, shortUrl):
        """Decodes a shortened URL to its original URL.
        
        :type shortUrl: str
        :rtype: str
        """
        return self._dict[shortUrl]
        
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))

c++代码:

#include <map>
using namespace std;
class Solution {
public:
    map<string,string> _map;
    int key=0;
    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        string txt="tinyurl"+to_string(key);
        _map[txt]=longUrl;
        key++;
        return txt;
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl) {
        return _map[shortUrl];
    }
};

// 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、付费专栏及课程。

余额充值