LeetCode算法题535. Encode and Decode TinyURL

LeetCode算法题535. Encode and Decode TinyURL

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.

题目的意思很简单就是要把一个例如 https://leetcode.com/problems/design-tinyurl 这样的长链接转化为 http://tinyurl.com/4e9iAk 这样的短链接,然后还能最后再转化回去。下面给出python3的解决方法:

  1. 定义两个函数encode()和decode(),模板已经有给出;
  2. 注意到短链接最后一共是有6个字符组成的字符串,由大小写字母和数字构成。这时候我们就可以使用python3中string库里提供的两个函数string.ascii_lettersstring.digits生成a-z,A-Z,0~9的字符串.
  3. 创建两个字典,longtoshort用来从长URL映射到短URL,它的索引是longUrl,值为shortUrl 。 shorttolong相反。
    longtoshort={}
    shorttolong={}
  4. 定义一个生成http://tinyurl.com/4e9iAk中4e9iAk这6个字符的函数
def key():
            sixletters=''
            t=''
            for i in range(6):
                t=letters[random.randint(0,10000)%62]   #从a~z,A~Z,0~9中随机选一个字符,连续6次
                sixletters+=t
            return sixletters   #返回6个随机字符
  1. 生成的6个字符拼接成短链接
if longUrl in longtoshort:
            return 'http://tinyurl.com/'+longtoshort[longUrl]
        else:
            key=key()
            longtoshort[longUrl]=key
            shorttolong[key]=longUrl
            return 'http://tinyurl.com/'+key
  1. 实现decode():只需要在shorttolong字典中查找,若存在就返回长链接。
def decode(self, shortUrl):
        key=shortUrl.split('/')[-1]
        if key in shorttolong:
            return shorttolong[key]
  1. LeetCode运行结果和提交结果。

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值