Saturday, October 10, 2020

535. Encode and Decode TinyURL ---M

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. 

A:

就是 base 62

class Solution {
public:

    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        string key = getRandom();
        while(M.find(key) != M.end()){
            key = getRandom();
        }
        M[key] = longUrl;
        return "http://tinyurl.com/"+key;
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl) {
        string str = "http://tinyurl.com/";        
        string key = shortUrl.substr(str.length());
        return M[key];
    }
private:
    unordered_map<string,string> M;
    string getRandom(){
        string res="";
        for(int i =0;i<6;i++){
            int v = rand() %62;
            char ch='a';
            if(v<=9){
                ch = '0'+v;
            }else if(v<36){
                ch = 'a'+ (v-10);
            }else{
                ch = 'A' + (v-36);
            }
        }
        return res;
    }
};

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

No comments:

Post a Comment