字符串统计
题目:
判断一个由a-z 这26 个字符组成的字符串中哪个字符出现的次数最多
输入:第1 行是测试数据的组数n,每组测试数据占1 行,是一个由a-z 这26 个字符组成的字符串,每组测试数据之间有一个空行,每行数据不超过1000 个字符且非空
输出:n 行,每行输出对应一个输入。一行输出包括出现次数最多的字符和该字符出现的次数,中间是一个空格。 如果有多个字符出现的次数相同且最多,那么输出ascii 码最小的那一个字符。
输入样例
2
abbccc
adfadffasdf
输出样例
c 3
f 4
import java.util.*;
public class poj4_2 {
public static void main(String args[]){
int[] abc;
String str;
int i = 0, p = 0;
Scanner r = new Scanner(System.in);
int n = r.nextInt();
abc = new int[26];
while(i<n)
{
str = new Scanner(System.in).nextLine();
while(p<str.length())
{
abc[str.charAt(p)-'a']++;
p++;
}
int max = 0;
for(int j = 0; j<26; j++)
{
if(abc[i]>abc[max]) max = i;
}
System.out.println(abc[max]);
i++;
}
}
}
[解决办法]
import java.util.*;public class poj4_2 { public static void main(String args[]){ int[] abc; String str; int i = 0, p = 0; Scanner r = new Scanner(System.in); int n = r.nextInt(); abc = new int[26]; while(i<n) { p = 0; str = new Scanner(System.in).nextLine(); while(p<str.length()) { abc[str.charAt(p)-'a']++; p++; } int max = 0; for(int j = 0; j<26; j++) { if(abc[j]>abc[max]) max = j; } System.out.println(abc[max]); for(int j=0; j<26; ++j){ //把计数数组再次清零 abc[j] = 0; } i++; } } }
[解决办法]
很久没写够java程序,java中字符加一个正数变为另一个字符都忘记怎么搞了。
不行试试下面这个
import java.util.*;public class poj4_2 { public static void main(String args[]){ int[] abc; String str; int i = 0, p = 0; Scanner r = new Scanner(System.in); int n = r.nextInt(); abc = new int[26]; String s = new String("abcdefghijklmnopqrstuvwxyz"); while(i<n) { System.out.println(i + "th round"); p = 0; str = new Scanner(System.in).nextLine(); while(p<str.length()) { abc[str.charAt(p)-'a']++; p++; } for(int j=0; j<26; ++j){ if(abc[j] != 0){ System.out.println(s.charAt(j) + " " + abc[j]);//辅助信息,可注释 } } int max = 0; for(int j = 0; j<26; j++) { if(abc[j]>abc[max]) max = j; } System.out.println("Result: " + s.charAt(max)+ " " + abc[max]); for(int j=0; j<26; ++j){ abc[j] = 0; } i++; } } }