Simple C++ solution without using a special character, but with a fixed number of digits as header.


  • 0
    S

    I see some solutions are using "@" or "#" as special character, and then try to split the encoded string using this character. They also put the length of the character before "@". But that shouldn't be allowed. What if we have "5@" as a string? In my solution, I used a fixed 8 digit header before each string to store its length. A better idea would be using 4 chars before each string to store its length as an integer. Feel free to implement it!

    class Codec {
    public:
    
        // Encodes a list of strings to a single string.
        string encode(vector<string>& strs) {
            string result;
            for (auto str:strs){
                result += intToString(str.size()) + str;
                //cout << result << endl;
            }
            return result;
        }
        string intToString(int n){
            if (n == 0) return "00000000";
            int digits = log(n)/log(10) + 1;
            string result = "";
            for (int i = 0; i < 8 - digits; ++i){
                result += '0';
            }
            cout << result << endl;
    
            return result + to_string(n);
        }
    
        // Decodes a single string to a list of strings.
        vector<string> decode(string s) {
            vector<string> result;
            int i = 0;
            while(i < s.size()){
                int str_length = stoi(s.substr(i, 8));
                i += 8;
                result.push_back(s.substr(i,str_length));
                i += str_length;
            }
            return result;
        }
    };
    

Log in to reply
 

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