Sharing my C++ solution


  • 0
    T
    class Codec {
    public:
    
        // Encodes a list of strings to a single string.
        string encode(vector<string>& strs) {
            string result;
            int n = strs.size(), i;
            for(i=0; i<n; i++)
            {
                result = result + to_string(strs[i].length()) + ',';
            }
            result = result + '|';
            for(i=0; i<n; i++)
                result = result + strs[i];
                
            return result;
        }
    
        // Decodes a single string to a list of strings.
        vector<string> decode(string s) {
            int posOfDivision = s.find_first_of('|');
            vector<int> sizes;
            int start=0, i;
            for(i=0; i<posOfDivision; i++)
            {
                if(s[i]==',')
                {
                    string tmp = s.substr(start, i-start);
                    sizes.push_back(atoi(tmp.c_str()));
                    start = i+1;
                }
            }
            start = posOfDivision+1;
            vector<string> result;
            for(i=0; i<sizes.size(); i++)
            {
                result.push_back(s.substr(start, sizes[i]));
                start = start + sizes[i];
            }
            
            return result;
        }
    };
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec;
    // codec.decode(codec.encode(strs));

Log in to reply
 

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