60ms AC in C++...Is there any flaw in my solution?


  • 0
    S
    // Encodes a list of strings to a single string.
    string encode(vector<string>& strs) {
        string lengthAppend;
        string encoded;
        for (int i = 0; i < strs.size(); i++) {
            int length = strs[i].size();
            lengthAppend += to_string(length) + "@";
            encoded += strs[i];
        }
        encoded = lengthAppend + "-" + encoded;
        return encoded;
    }
    
    // Decodes a single string to a list of strings.
    vector<string> decode(string s) {
        int line_pos = s.find_first_of('-');
        string encoded = s.substr(line_pos+1, s.size()-line_pos-1);
        vector<string> decoded;
        int length_index_start = 0;
        int current_string = 0;
        while (length_index_start < line_pos) {
            int at_pos = s.find_first_of('@', length_index_start);
            string length_str = s.substr(length_index_start, at_pos-length_index_start);
            length_index_start = at_pos + 1;
            
            int length = stoi(length_str);
            decoded.push_back(encoded.substr(current_string, length));
            current_string += length;
        }
        return decoded;
    }

Log in to reply
 

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