C++ summary string encoder & decoder


  • 0
    F

    let us check the count and say problem first :

    Count and Say

    class Solution {
    public:
        string countAndSay(int n) {
            if (n == 0) return "";
            string result = "1";
            while (--n) {
                string cur = "";
                for (int i = 0; i < result.size(); i++) {
                    int count = 1; 
                    while ((i+1) < result.size() && result[i] == result[i+1]) {
                        count++;
                        i++;
                    }
                    cur += to_string(count) + result[i];
                }
                result = cur;
            }
            return result;
        }
    };
    
    

    Let us check another problem :

    Encode and Decode Strings

    class Codec {
    public:
        // Encodes a list of strings to a single string.
        string encode(vector<string>& strs) {
            string result;
            for (auto a : strs) {
                result.append(to_string(a.size())).append("/").append(a);
            }
            return result;
        }
        // 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 found = s.find("/", i);
                int len = stoi(s.substr(i, found));
                result.push_back(s.substr(found + 1, len));
                i = found + len + 1;
            }
            return result;
        }
    };
    

Log in to reply
 

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