题目描述
给定一个字符串str,返回str的统计字符串。例如“aaabbbbcccd”的统计字符串为“a_3_b_4_c_3_d_1”。
import java.util.Scanner;
public class Main {
public static StringBuilder getResult(String str) {
StringBuilder result=new StringBuilder();
int sum=1;
char ch=str.charAt(0);
for(int i=1;i<str.length();i++) {
if(ch==str.charAt(i)) {
sum++;
}else {
result.append(ch+"_"+sum+"_");
sum=1;
ch=str.charAt(i);
}
}
result.append(ch+"_"+sum);
return result;
}
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String str=scan.nextLine();
System.out.print(getResult(str));
scan.close();
}
}