60ms c++ solution that works for all character set and doesn't use separator

  • 2

    The idea of encoding is, concatenate all strings of input into a string, and prefix that string with each input strings' length. For example, when input is ["a2", "a|a3", "ccc4"], the encoded string is "5,2,4,4a2a|a3ccc4".
    The 2,4,4 is the length of each string in input. The 5 before 2,4,4 is length of the "2,4,4" string.
    When decoding, first get 5, then we can get "2,4,4", then we separate the rest string into vector

    string encode(vector<string>& strs) {
        string res = "";
        string temp = "";
        for(string s:strs){
            res += s;
            temp += to_string(s.length());
            temp += ",";
        if(temp.length() != 0) temp.pop_back();
        res = to_string(temp.length())+","+temp+res;
        return res;
    // Decodes a single string to a list of strings.
    vector<string> decode(string s) {
        vector<string> res;
        if(s.length() == 0) return res;
        int curr = 0;
        int prefix_len = stoi(s.substr(0, curr));
        string prefix = s.substr(curr+1, prefix_len);
        string concat_str = s.substr(curr+prefix_len+1, s.length()-curr-prefix_len-1);
        stringstream ss(prefix);
        string pos;
        int start = 0;
        while(getline(ss, pos, ',')){
            int temp = stoi(pos);
            res.push_back(concat_str.substr(start, temp));
            start += temp;
        return res;

Log in to reply

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