535. Encode and Decode TinyURL
Problem description:
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
Solution:
- use two unordered_map to store the relation of original url and shorten url,
shot2long
andlong2short
. - The whole process can be divided into 2 parts
- encode:
- input would be original string
- create a random
6 character string
, which means we need to have a dictionary to search which character to use. - after created
6 character string
, need to check whether if it’s already used.
- decode:
- the input would be shorten url string
- extract 6 character string from input, search whether it is stored in the map.
- encode:
1 | class Solution { |