【发布时间】:2015-10-06 23:34:47
【问题描述】:
我得到了一个面试问题,以输出一个字符出现频率最高的情况。
给定这个字符串“aaxxaabbaa”。字符“a”是最常见的。
以下代码是我在互联网上搜索的。注意:我用 2 个效率低的循环来实现它(不同的主题)
public static char findMostUsedChar(String str){
char maxchar = ' ';
int maxcnt = 0;
// if you are confident that your input will be only ascii, then this array can be size 128.
// Create a character counter
**int[] charcnt = new int[Character.MAX_VALUE + 1];**
for(int i = 0; i < str.length()-1; i++){
char **ch** = str.charAt(i);
// increment this character's cnt and compare it to our max.
if (**charcnt[ch]**++ >= maxcnt) {
maxcnt = charcnt[ch];
maxchar = ch;
}
}
return maxchar;
}
他们声明了一个 int 数组,在特定索引(即“a”)处找到字符,然后将其用作索引。 在 eclipse 中的调试器上跟踪代码后,我仍然不明白如何使用字符来表示 int 索引而不显式转换它或使用 charVal.getNumericValue()??甚至大多数 S.O. char 到 int 主题显式转换。
提前致谢。
【问题讨论】:
标签: java char int type-conversion