#1、字符串aabcccccaaa
会变为a2b1c5a3
"abbccd"压缩后为"a1b2c2d1",比原字符串长度更长,输出之前原串
#2、解题思路:
1、双指针记录每次重复的个数
2、使用str+=S[i];节省内存
3、S.length(),返回长度
4、不知道每次的长度,所以使用while()
#、3代码
class Solution {
public:
string compressString(string S) {
int n=S.length();
string res;
int i=0;
while(i<n)
{
int j=i;
while(j<n && S[j]==S[i])
j++;
res+=S[i];
res+=to_string(j-i);
i=j;
}
if(res.length()<S.length())
return res;
else
return S;
}
};