使用append而不是使用+號來串接字符串

 

最佳實踐:在字符串編程的時候,儘可能使用append,而不是使用+號,因爲使用+號的話用導致內存的拷貝,這樣可能會超出內存限制.

 

 

字符串壓縮 https://leetcode-cn.com/problems/compress-string-lcci/

class Solution {
public:
    string compressString(string S) {
        //每次遇到不一樣的就進行更新操作
        if(S.size() ==0 ) return "";

        //爲了普遍性
        char ch =S[0];//一開始是空字符
        int count = 1;
        string res;
        //aabbb
        
        for(int i = 1; i < S.size(); i++){
            if(ch != S[i]){
                //做清算
              //  res = res + ch + to_string(count);
                res.append(ch+to_string(count));
                ch = S[i];
                count = 1;
            }else
                count ++;
        }



        //結尾做清盤
      //  res = res + ch + to_string(count);
        res.append(ch+to_string(count));
        if(res.size() >= S.size()) return S;
        return res;

    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章