leetcode/0535_encode-and-decode-tinyurl/python3/solution.py

38 lines
914 B
Python

# NOTE: This one is an open-ended question, and relevant to system design. Refer
# the notes.
import string
import random
class Codec:
store = {}
base = 'https://tiny.url/'
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
tiny = None
while True:
tiny = ''.join(random.choices(string.ascii_letters + string.digits, k = 5))
if tiny not in self.store:
break
self.store[tiny] = longUrl
return f'{self.base}{tiny}'
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
_, tiny = shortUrl.split(self.base)
return self.store[tiny]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))