535. Encode and Decode TinyURL

偷懒用了hash,自己写letter+digit的随机抽取,可以固定长度+增加最大容量,懒得写了这里...

class Codec:
    def __init__(self):
        self.map_ = dict()

    def encode(self, longUrl: str) -> str:
        """Encodes a URL to a shortened URL.
        """
        self.map_[hash(longUrl)] = longUrl
        return "http://tinyurl.com/" + str(hash(longUrl))

    def decode(self, shortUrl: str) -> str:
        """Decodes a shortened URL to its original URL.
        """
        return self.map_[int(shortUrl.lstrip("http://tinyurl.com/"))]
    

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

Last updated

Was this helpful?