Leetcode string compression for daily question

The topic is simple, but there are still things to record

Subject: https://leetcode-cn.com/problems/compress-string-lcci/

class Solution {
public:
    string compressString(string S) {
        int len=S.length();
        if (len==0) return S;
        string res="";
    
        char c=S[0];
        int cnt=1;
        for (int i=1;i<len;i++)
        if (S[i]==c){
            cnt++;
        }
        else{
            res+=c+to_string(cnt);
            cnt=1;
            c=S[i];
        }
        res+=c+to_string(cnt);
        if (res.length()<len) return res;
        else return S;
    }
};

Here is a point, the first two submissions I had an error that exceeded the memory limit

The reason is that I wrote res+=c+to_string(cnt); as res=res+c+to_string(cnt);

Here I do my own explanation, I don't know if it is right, because the calculation result on the right of "=" is in the temporary space, so if you put a large calculation result directly on the right, it may exceed this temporary space. So use "+="

However, there is a problem when using addition and so on, that is, one of the left and right operands of the string "+" operator must be of string type, but chars cannot be added (cannot only have char type characters.)

Thanks to https://blog.csdn.net/liuchuo/article/details/51994235 and its comments for reminding me.

Guess you like

Origin blog.csdn.net/hbhhhxs/article/details/104906850