题目描述:输入一串字符串,aaaabbbccc,对它进行压缩,输出 a4b3c3,如果压缩后它的长度和原来一样,则输出原来的字符串
输入示例: 输入示例:
aaabbbccc abc
输出:
a3b3c3 abc
import java.util.Scanner;
public class Demo36压缩密码{
// 从头开始遍历,j每次从i后面的那个值开始遍历,相等sum++,不相等则跳出循环
// 再次更新i的值,从,j再从i后面进行遍历,以此类推
public static String stringToreduce(String str){
StringBuilder builder = new StringBuilder();
int count = str.length();
int i = 0;
while (i<count){
char c1 = str.charAt(i);
int sum=1;
for (int j = i+1; j<count;j++) {
char c2 = str.charAt(j);
if (c2 == c1) {
sum++;
}else {
break;
}
}
if(sum>1) {
builder.append(c1).append(sum);
}else{
builder.append(c1);
}
i=i+sum;
}
return builder.toString();
}
public static void main(String[] args){
Scanner s = new Scanner(System.in);
String str = s.nextLine();
String str1 = stringToreduce(str);
System.out.println(str1);
}
}