我接受了一个面试问题,以输出最常出现的角色。
鉴于此字符串" 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数组,找到了特定索引处的字符(即&#39; a&#39;)然后用作索引。 在eclipse中的调试器上跟踪代码之后,我仍然不明白如何使用字符来表示int索引而不显式地使用它或使用charVal.getNumericValue()?甚至大多数S.O. char到int主题显式转换。
提前致谢。
答案 0 :(得分:5)
Array access expressions会进行隐式一元数字提升,这会将表达式扩展为int
。
索引表达式经历一元数字促销(第5.6.1节)。
char
数据类型通过其Unicode值扩展为int
,例如'A'
- &gt; 65
。