LeetCode_Encode and Decode TinyURL

908 ワード

class Codec:
    
    def __init__(self):
        self.lookup = []

    def encode(self, longUrl):
        """Encodes a URL to a shortened URL.
        
        :type longUrl: str
        :rtype: str
        """
        N = len(self.lookup)
        print("N in encode", N)
        self.lookup.append(longUrl)
        return 'http://tinyurl.com/' + str(N)
        

    def decode(self, shortUrl):
        """Decodes a shortened URL to its original URL.
        
        :type shortUrl: str
        :rtype: str
        """
        r = int(shortUrl.split('/')[-1])
        return self.lookup[r]
        

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))

原理:ハッシュ・テーブルの使用


つまり、キー値は0です.
キーの値を指定します.
元のlongurlを出力