字符串—压缩字符串
程序员文章站
2024-03-14 14:12:22
...
问题
将一个字符串进行压缩,例如 aabcccc 压缩后为a2b1c4如果压缩后字符串没有变短则返回原字符串,保证输入合法。
实现
从前往后顺次进行处理并添加到新字符串中。
/**
* 1.5问题: 压缩字符串。例如 aabcccc 压缩后为a2b1c4如果压缩后字符串没有变短则返回原字符串
* 思路:使用StringBuilder进行顺次处理
* time:o(n)
* space:o(n)
*/
public static String compressBetter(String s){
StringBuilder stringBuilder = new StringBuilder();
char last = s.charAt(0); //recode the pre char
int length = s.length();
int count = 1;
for(int i = 1; i < length; i++){
if(s.charAt(i) == last){
count ++;
}else{
stringBuilder.append(last);
stringBuilder.append(count);
last = s.charAt(i);
count = 1;
}
}
// solve the last char
stringBuilder.append(last);
stringBuilder.append(count);
// judge the length
// maybe you can judge the length in the start, but it will increase the complexity
return stringBuilder.length() > length ? s : stringBuilder.toString();
}