题目链接:535. TinyURL 的加密与解密
在内部维护一个短 url 到长 url 的映射。
考虑大规模的短 url,可能会存在哈希冲突,需要引入随机化/编号。
考虑到分布式,需要雪花算法之类的复杂发号算法。
import string
from urllib.parse import urlparse
class NumberEncoder:
alphabet = string.digits + string.ascii_letters
idx = {k: i for i, k in enumerate(alphabet)}
sign = '~'
@classmethod
def encode(cls, v: int) -> str:
u, sign = '', ''
if v < 0:
sign = '~'
v = -v
if 0 <= v < len(cls.alphabet):
return sign + cls.alphabet[v]
while v != 0:
v, i = divmod(v, len(cls.alphabet))
u = cls.alphabet[i] + u
return u + sign
class Codec:
def __init__(self):
self.urls: dict[str, str] = dict()
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
path = f'/{NumberEncoder.encode(hash(longUrl))}'
self.urls[path] = longUrl
return f'http://s.t{path}'
def decode(self, shortUrl: str) -> str:
return self.urls.get(urlparse(shortUrl).path, '')