[C++ with header]


  • 0
    H
    class Codec {
    public:
    
        // Encodes a list of strings to a single string.
        string encode(vector<string>& strs) {
            string size = to_string(strs.size()) + " ";
            string lens = "", content = "";
            for (string sit : strs) {
                lens += to_string(sit.size()) + " ";
                content += sit;
            }
            return size + lens + content;
        }
    
        // Decodes a single string to a list of strings.
        vector<string> decode(string s) {
            int idx = 0, size = 0;
            while (s[idx] != ' ') size = size * 10 + (s[idx++] - '0');
            ++idx;
            
            vector<int> lens;
            for (int i = 0; i < size; ++i) {
                int len = 0;
                while (s[idx] != ' ') len = len * 10 + (s[idx++] - '0');
                lens.push_back(len);
                ++idx;
            }
            
            vector<string> res;
            for (int i = 0; i < size; ++i) {
                res.push_back(s.substr(idx, lens[i]));
                idx += lens[i];
            }
            return res;
        }
    };
    

Log in to reply
 

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