Skip to content

535. Encode and Decode TinyURL

#213

Problem link

https://leetcode.com/problems/encode-and-decode-tinyurl/

Problem Summary

tinyurl 같은 것을 구현하는 문제.

Solution

... medium 치고 너무 쉬운데... 그냥 daily 라서 풀어보았다.

단순히 입력받는 것을 리턴해도 통과가 된다... 하지만 아무 의미가 없으니 간단하게 짜보자.

간단하게 하는 방법으로 id 카운터 값을 놓고 1씩 증가하면서 shorturl을 생성할 수 있다. map으로 관리해주면 매우 간단하게 가능하다.

Source Code

class Codec:
    def __init__(self):
        self.url_map = {}
        self.url_id = 0

    def encode(self, longUrl: str) -> str:
        """Encodes a URL to a shortened URL.
        """
        self.url_id += 1
        short_url = "http://tinyurl.com/" + str(self.url_id)
        self.url_map[short_url] = longUrl
        return short_url

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

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