13. Encode and Decode TinyURL

Note: This is a companion problem to the System Design problem: Design TinyURL.

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:

class Solution
{
public:
    // Encodes a URL to a shortened URL.
    string chars = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    int len = chars.length();
    string baseUrl = "http://tinyUrl.com/";
    unordered_map<string, string> shortner;
    unordered_map<string, string> revKey;

    string encode(string longUrl)
    {
        if (revKey.find(longUrl) != revKey.end())
        {
            string key = revKey[longUrl];
            return baseUrl + key;
        }
        
        string key = "";
        for (int i = 0; i < 6; i++)
        {
            char ch = chars[rand() % len];
            key += ch;
        }

        if (shortner.find(key) == shortner.end())
        {
            shortner.insert({key, longUrl});
            revKey.insert({longUrl, key});
        }

        return baseUrl + key;
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl)
    {
        string key = shortUrl.substr(19, 6);
        string longUrl = shortner[key];
        return longUrl;
    }
};

Last updated