最佳實踐:在字符串編程的時候,儘可能使用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;
}
};