美文网首页
[LeetCode]535. Encode and Decode

[LeetCode]535. Encode and Decode

作者: Eazow | 来源:发表于2017-04-28 15:04 被阅读730次

    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.

    方法

    提供一个map和变量i,每来一个url的时候i++,将urli的对应关系存入map即可

    python代码
    class Codec:
    
        def __init__(self):
            self.map = {}
            self.i = 0
        
        def encode(self, longUrl):
            """Encodes a URL to a shortened URL.
            :type longUrl: str
            :rtype: str
            """
            self.i += 1
            self.map[self.i] = longUrl
            return "http://tinyurl.com/" + str(self.i)
    
    
        def decode(self, shortUrl):
            """Decodes a shortened URL to its original URL.
            :type shortUrl: str
            :rtype: str
            """
            return self.map[int(shortUrl.split('/')[-1])]
    
    # Your Codes object will be instantiated and called as such:
    # codec = Codec()
    # codec.decode(codec.encode(url))
    
    url = "https://leetcode.com/problems/design-tinyurl";
    codec = Codec()
    assert codec.decode(codec.encode(url)) == url
    

    相关文章

      网友评论

          本文标题:[LeetCode]535. Encode and Decode

          本文链接:https://www.haomeiwen.com/subject/sytazttx.html