【发布时间】:2013-08-01 13:11:02
【问题描述】:
到目前为止,这是我尝试过的:
public class CharacterCounter {
public static void main(String[] args){
String string = "sashimi";
int count = 0;
for(int i =0; i < string.length(); i++){
if(string.charAt(i) == 'i'){
count++;
}
}
System.out.println("The number of letter i is " + count);
}
}
输出:
The number of letter i is 2
但我想做的是,程序应该计算出现次数最多的字符。
例如这里的字符串是SASHIMI,输出应该是:
the number of letter S is 2
the number of letter I is 2
我被这个问题困住了。我需要你的帮助。谢谢。
【问题讨论】:
-
您应该使用
HashMap <Character, Integer>。关键是一个字符。该值为出现的次数。 -
也许你应该使用某种map,其中字符是键,它的频率是值。然后,您可以遍历映射并找到具有最高值的键。
-
int[1<<16]也会做得很好,而且性能要好得多。事实上,速度很快。 -
@Marko 你能详细点吗?我不明白它的作用。
-
@ArnaudDenoyelle 请参阅下面的答案。
标签: java