I was given an interview question to output the most frequent occurrence of a character.
Given this string "aaxxaabbaa". The character 'a' is the most frequent.
The following code was something that I found searching on the internet. Note: I implemented it with 2 loops which is in-efficient (different topic)
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;
}
They declared an int array, found the character at a specific index (i.e. 'a') then used as an index. After tracing the code out on the debugger in eclipse, I still don't understand how using a character to represent an int index works without explicitly casting it or using charVal.getNumericValue()?? Even most of the S.O. char to int topics explicitly cast.
Thanks in advance.