字符统计2
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
输入英文句子,输出该句子中除了空格外出现次数最多的字符及其出现的次数。
Input
输入数据包含多个测试实例,每个测试实例是一个长度不超过100的英文句子,占一行。
Output
逐行输出每个句子中出现次数最多的字符及其出现的次数(如果有多个字符的次数相同,只输出ASCII码最小的字符)。
Sample Input
I am a student
a good programming problem
ABCD abcd ABCD abcd
bbaa iou
Sample Output
a 2
o 4
A 2
a 2
注意:用String型輸入字符串,要排除空格的个数
AC代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner mi = new Scanner(System.in);
while (mi.hasNext()) {
String str = mi.nextLine();
int n = str.length();
int[] a = new int[150]; //a的ASCII码值为97,a[]最小为97+26
int x, t = 0, max = 0;
char ch = '0'; //t 和 ch 必须初始化
for (int i = 0; i < n; i++) {
if (str.charAt(i) != ' ') {
x = str.charAt(i);
a[x]++;
if (max < a[x]) {
ch = str.charAt(i);
max++;
t = x;
}
if (max == a[x]) {
if (t > x) {
ch = str.charAt(i);
}
}
}
}
System.out.println(ch + " " + max);
}
mi.close();
}
}
——————
余生还请多多指教!