All*_*len 0 java int type-conversion char
我接受了一个面试问题,以输出最常出现的角色.
鉴于此字符串"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;
}
Run Code Online (Sandbox Code Playgroud)
他们声明了一个int数组,在特定索引(即'a')处找到该字符,然后用作索引.在eclipse中的调试器上跟踪代码之后,我仍然不明白如何使用字符来表示int索引,而无需显式地使用它或使用charVal.getNumericValue()?甚至大多数SO char到int主题都明确地转换了.
提前致谢.