535. Encode and Decode TinyURL (Medium)

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: 6ms

class Solution {
public:

    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        if (l2s.count(longUrl)) return prefix+l2s[longUrl];
        string cnt = to_string(l2s.size());
        l2s[longUrl] = cnt;
        s2l[cnt] = longUrl;
        return prefix+cnt;
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl) {
        string cnt = shortUrl.substr(prefix.size());
        return s2l[cnt];
    }
private:
    string prefix = "http://tinyurl.com/";
    unordered_map<string, string> l2s, s2l;
};

// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));

results matching ""

    No results matching ""