题目描述
遍历法
在C++中
- s += s1 等价于s.append(s1),不产生新的对象。不利用额外空间
- s = s + s1 是先创建一个string对象,再把s1的内容赋值给s(s的地址不变),利用额外空间
string compressString(string S) {
if(S.size() == 1) return S;
string res;
char pre = S[0];
res.push_back(pre);
int count = 1;
for(int i=1; i<S.size(); i++){
if(pre == S[i]){
count++;
}else{
res += to_string(count);
res.push_back(S[i]);
count = 1;
}
pre = S[i];
}
res += to_string(count);
return res.size() < S.size() ? res : S;
}
双指针法
string compressString(string S) {
if(S.size() == 1 || S.size() == 2) return S;
string res;
int i = 0;
while(i < S.size()){
res.push_back(S[i]);
int j = i + 1;
while(j < S.size() && S[i] == S[j]) j++;
res += to_string(j - i);
i = j;
}
return res.size() < S.size() ? res : S;
}