**题目:**字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。 示例: 提示:
字符串长度在[0, 50000]范围内。
方法:模拟
class Solution {
public String
compressString(String S
) {
int i
=1;
StringBuffer sb
=new StringBuffer();
if(S
.length()==0||S
==null
)return S
;
char pre
=S
.charAt(0);
int count
=1;
sb
.append(S
.charAt(0));
boolean flag
=false;
while(i
<S
.length()) {
if(S
.charAt(i
)!=pre
) {
pre
=S
.charAt(i
++);
sb
.append(count
);
sb
.append(pre
);
count
=1;
flag
=true;
}else {
count
++;
i
++;
flag
=false;
}
}
String res
=sb
.append(count
).toString();
return res
.length()<S
.length()?res
:S
;
}
}
转载请注明原文地址: https://lol.8miu.com/read-38831.html