到目前为止,这是我尝试过的:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
The number of letter i is 2
Run Code Online (Sandbox Code Playgroud)
但我想做的是,该程序应该计算最常出现的字符.
例如,这里的字符串是SASHIMI,输出应该是:
the number of letter S is 2
the number of letter I is 2
Run Code Online (Sandbox Code Playgroud)
我遇到了这个问题.我需要你的帮助.谢谢.
这将是最快的方式:
final int[] counts = new int[1<<16];
for (char c : <your_string>)
counts[c]++;
Run Code Online (Sandbox Code Playgroud)
(我刚刚勾勒出迭代你所有字符的部分,我相信这很容易,而且与这个问题没有直接关系).
我HashMap用三种弦长来对付我的方法:
这些是结果:
Benchmark Mode Thr Cnt Sec Mean Mean error Units
testArray1 thrpt 1 5 5 6.870 0.083 ops/msec
testArray2 thrpt 1 5 5 6.720 0.374 ops/msec
testArray3 thrpt 1 5 5 3.770 0.019 ops/msec
testHashMap1 thrpt 1 5 5 1269.123 251.766 ops/msec
testHashMap2 thrpt 1 5 5 12.776 0.165 ops/msec
testHashMap3 thrpt 1 5 5 0.141 0.005 ops/msec
Run Code Online (Sandbox Code Playgroud)
他们的意思是什么?是的,将完整的512K内存块初始化为零是昂贵的.但在付款之后,我的数组算法甚至几乎没有注意到成千上万的人物.HashMap另一方面,这种方法对于非常短的弦乐来说要快得多,但是音阶会急剧恶化.我猜这个交叉是大约2k弦长.
我认为这样的字符统计统计数据通常是针对大量的文本语料库而不是像你的名字和姓氏这样的东西.
当然,如果您可以假设不使用完整的UTF-16码点范围,则可以大大提高阵列方法的性能.例如,如果使用仅容纳最低1024个代码点的阵列,则性能会上升到470 ops/msec.