C++ encode string with sizes


  • 0
    G
    class Codec {
    public:
    
        // Encodes a list of strings to a single string.
        string encode(vector<string>& strs) {
            string result;
            
            ostringstream ss;
            ss << strs.size();
            result = ss.str() + " ";
            
            for(auto &s : strs){
                ostringstream ss;
                ss << s.size();
                result += ss.str() + " " + s;
            }
            
            return result;
        }
    
        // Decodes a single string to a list of strings.
        vector<string> decode(string s) {
            
            size_t  first = s.find(" ");
            string temp = s.substr(0,first);
            istringstream ss(temp);
            int size = 0;
            ss >> size;
            s = s.substr(first + 1);
            vector<string> result;
            
            for(int i = 0; i < size; ++i){
                size_t first = s.find(" ");
                string temp = s.substr(0,first);
                istringstream ss(temp);
                int size = 0;
                ss >> size;
                string str = s.substr(first + 1,size);
                result.push_back(str);
                s = s.substr(first + 1 + size);
            }
            
            return result;
        }
    };
    

Log in to reply
 

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