leetcode 每日一题 之 字符串压缩

题目很简单,但是需要记录的东西还是有的

题目: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;
    }
};

这里记录一个点,前两次提交我出现了超出内存限制的错误

原因是我把res+=c+to_string(cnt);写成了res=res+c+to_string(cnt);

这里我做一下自己的解释,不知道对不对,因为“=”右边的计算结果存在临时空间中,所以如果把很大的计算结果直接放在右边,那么可能会超出这个临时空间。所以使用“+=”

但是使用加等呢,也有一个问题,就是string“+”操作符的左右操作数必须有一个为string类型 ,但char之间不能相加(不能只有 char类型的字符。)

感谢https://blog.csdn.net/liuchuo/article/details/51994235及其评论给我的提醒。

猜你喜欢

转载自blog.csdn.net/hbhhhxs/article/details/104906850
今日推荐