leetcode 535. Encode and Decode TinyURL (python)

451 阅读1分钟

描述

TinyURL is a URL shortening service where you enter a URL such as leetcode.com/problems/de… and it returns a short URL such as 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.

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

解析

根据题意,不限方法将给出的 longUrl 编码为以 tinyurl.com/ 开头的字符串,并且能解码得到原 longUrl 。先将 longUrl 通过 hash 得到一个数字,然后将其作为 key ,longUrl 作为 value 保存在字典里供后面解码使用,然后将数字转化为字符串类型拼接到 tinyurl.com/ 后面即可得到 shortUrl 。在解码的时候,只需要将 shortUrl 去掉 tinyurl.com/ 部分,将剩下的部分转换为 int 类型,利用字典找出原字符串即可。

解答

class Codec:
    def __init__(self):
        self.url_table = dict()
        self.header = 'http://tinyurl.com/'
        
    def encode(self, longUrl) :
        url_id = hash(longUrl)
        short_url = self.header + str(url_id)
        self.url_table[url_id] = longUrl
        return short_url

    def decode(self, shortUrl):
        url_id = int(shortUrl.lstrip(self.header))
        return self.url_table[url_id]
        	      
		

运行结果

Runtime: 24 ms, faster than 43.61% of Python online submissions for Encode and Decode TinyURL.
Memory Usage: 13.3 MB, less than 95.49% of Python online submissions for Encode and Decode TinyURL.

原题链接:leetcode.com/problems/en…

您的支持是我最大的动力