python--leetcode 535. Encode and Decode 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.

这一题还是比较有意思的,题目意思就是说输入一个网址,让你用算法缩短这个网址,而且能否复原原网址。

当然这一题可以耍点小聪明就过了,直接return longurl 和return shorturl返回原地址。不过这并非我们刷leetcode的本意。

下面上代码,我一会再解释代码的意思:

class Codec:
    import string
    letters = string.ascii_letters + string.digits  #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
    full_tiny = {}
    tiny_full = {}
    global_counter = 0

    def encode(self, longUrl):
        """Encodes a URL to a shortened URL.

        :type longUrl: str
        :rtype: str
        """

        def decto62(dec):
            ans = ""
            while 1:
                ans = self.letters[dec % 62] + ans
                dec //= 62
                if not dec:
                    break
            print('ans:',ans)
            return ans

        suffix = decto62(self.global_counter)
        if longUrl not in self.full_tiny:
            self.full_tiny[longUrl] = suffix
            self.tiny_full[suffix] = longUrl
            self.global_counter += 1
        return "http://tinyurl.com/" + suffix

    def decode(self, shortUrl):
        """Decodes a shortened URL to its original URL.

        :type shortUrl: str
        :rtype: str
        """
        idx = shortUrl.split('/')[-1]
        print('fulltiny',self.full_tiny,self.tiny_full)
        if idx in self.tiny_full:
            return self.tiny_full[idx]
        else:
            return None

codec = Codec()
url='fffffffffff'
print(codec.decode(codec.encode(url)))
这里会输出以下内容:

ans: a
fulltiny {'fffffffffff': 'a'} {'a': 'fffffffffff'}
fffffffffff

解题思路:将输入的长地址与生成的短地址通过字典一一对应。dector62方法就是生成短地址的方法,通过global_counter的递增并取余,来获得短地址。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哎呦不错的温jay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值