1. 程式人生 > >leetcode-535. TinyURL 的加密與解密

leetcode-535. TinyURL 的加密與解密

pri sign name key tin zab you 加密 {}

TinyURL是一種URL簡化服務, 比如:當你輸入一個URL https://leetcode.com/problems/design-tinyurl 時,它將返回一個簡化的URL http://tinyurl.com/4e9iAk.

要求:設計一個 TinyURL 的加密 encode 和解密 decode 的方法。你的加密和解密算法如何設計和運作是沒有限制的,你只需要保證一個URL可以被加密成一個TinyURL,並且這個TinyURL可以用解密方法恢復成原本的URL。

思路:

  首先讀懂題意,從更高層次看,我們要做的是將長url(長字符串)映射為短url(短字符串)。

  首先想到的可能是找到某種映射關系,將長url映射為短url,但難度有點大。

  換一種思考的方式,我們對每個長url隨機生成沒有映射長url的短字符串,並記錄下長短url之間映射關系,然後在解碼的時候去查表即可。

代碼:

import random

class Codec:
    def __init__(self):
        self.code = 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
        self.long_to_short = {}
        self.short_to_long = {}

    def encode(self, longUrl):
        
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str """ if longUrl in self.long_to_short.keys(): return self.long_to_short.get(longUrl) else: encode = self.encodeUrl() while encode in self.short_to_long.keys(): encode
= self.encodeUrl() self.long_to_short[longUrl] = encode self.short_to_long[encode] = longUrl return encode def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str """ return self.short_to_long.get(shortUrl) if shortUrl in self.short_to_long.keys() else ‘‘ # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url)) def encodeUrl(self): return ‘‘.join([random.choice(self.code) for _ in range(6)]) if __name__ == __main__: codec = Codec() print(codec.decode(codec.encode("https://leetcode.com/problems/design-tinyurl")))

leetcode-535. TinyURL 的加密與解密