The Standard C++ Solution


  • -1
    H
    class Solution {
    public:
    
        // Encodes a URL to a shortened URL.
        
        string encode(string longUrl) {
            int num = rand()%1000000007;
            m[num] = longUrl;
            stringstream ss;
            while(num > 0) {
                int m = num%62;
                num /= 62;
                char ch = intToChar(m);
                ss << ch;
            }
            // string ret = ss.str();
            return ss.str();
        }
    
        // Decodes a shortened URL to its original URL.
        string decode(string shortUrl) {
            int key(0);
            for(auto it = shortUrl.rbegin(); it != shortUrl.rend(); it++)
                key = key*62 + charToInt(*it);
            return m[key];
        }
    private:
        char intToChar(int x) {
            if(x < 26)
                return 'a' + x;
            if(x < 52)
                return 'A' + (x - 26);
            return '0' + (x - 52);
        }
        int charToInt(char c) {
            if(c >= 'a' and c <= 'z')
                return c - 'a';
            if(c >= 'A' and c <= 'Z')
                return (c - 'A' + 26);
            return (c - '0' + 52);
        }
        unordered_map<int, string> m;
        
    };
    
    // Your Solution object will be instantiated and called as such:
    // Solution solution;
    // solution.decode(solution.encode(url));
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.