Skip to main content

535. Encode and Decode TinyURL

Python

import random
from urllib.parse import urljoin
from string import ascii_letters, digits

class Codec:
CHARS = ascii_letters + digits
BASE_URL = 'https://tinyurl.com/'

def __init__(self):
self.mapper = dict()
self.used = set()

def _generate(self):
return ''.join([random.choice(self.CHARS) for i in range(8)])

def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
cand = self._generate()
while cand in self.used:
cand = self._generate()

url = urljoin(self.BASE_URL, cand)
self.mapper[url] = longUrl
self.used.add(cand)
return url

def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
if shortUrl not in self.mapper:
return
return self.mapper[shortUrl]

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