题解 | #字符统计#
字符统计
http://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
import java.util.Scanner; public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.next();
method(str);
System.out.println();
}
}
public static void method(String str){
//只有小写字母和数字(总共36个字符)
int[] arr = new int[36];
//对str字符串中的字符进行计数
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
arr[test(c)]++;
}
//找出最大数
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if(arr[i]>max){
max = arr[i];
}
}
//按顺序输出 arr[i]=max 对应的字符,
//然后max-1,再按顺序输出 arr[i]=max 对应的字符,
//循环直到 max=0 再退出
while (max != 0){
for (int i = 0; i < arr.length; i++) {
if(arr[i] == max){
System.out.print(test2(i));
}
}
max --;
}
}
//返回字符在数组中对应的索引
public static int test(char c){
return "0123456789abcdefghijklmnopqrstuvwxyz".indexOf(c);
}
//根据索引返回对应字符
public static char test2(int i){
return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(i);
}
}