Encode and Decode TinyURL

Problem Id: 535 Difficulty: Medium


Intuition

Solution


#!/usr/bin/env python
# coding=utf-8
#
# Author: Lucas
# Date: 2019-08-20 23:37:12


import random


class Codec:
    def __init__(self):
        self.mapping = {}
        self.index = 1

    def encode(self, longUrl):
        """Encodes a URL to a shortened URL.

        :type longUrl: str
        :rtype: str
        """
        self.mapping[self.index] = longUrl
        self.index += 1
        return str(self.index - 1)

    def decode(self, shortUrl):
        """Decodes a shortened URL to its original URL.

        :type shortUrl: str
        :rtype: str
        """
        return self.mapping[int(shortUrl)]


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