简体   繁体   中英

Need to find the character most frequent in a string and return the number of times it appears

public static int mostCommonChar(String foog){
    int anArray[] = new int[foog.length()];


    int foober = 0;
    char f;
    for (int i = 0; i > foog.length(); i++){
        f = foog.charAt(i);
        foober = 1;

        for (int j = i + 1; j < foog.length(); j++){
            if (f == foog.charAt(j)){
                foober++;
            }

            anArray[i] = foober;
        }

    }
    Arrays.sort(anArray);
    int max = anArray[anArray.length - 1];
    System.out.println(max);
    return 5;
}

The return 5 is just so it works, then when it does I'll return max but for now I have to print it.

Now I'm pretty sure I messed up a lot of things. But I think that they highest number would still go to the end and by sorting the array I can retrieve the number of times the most frequent character appeared.

For the string, I used "habakkuk" and I expected "3" to print given there are 3 k's but it didn't. Could anyone tell me what I am doing wrong? Thanks!

You just have a small typo

for (int j = i + 1; j > foog.length(); j++)

should be

for (int j = i + 1; j < foog.length(); j++)

Sidenote: You can improve your algorithm. Right now it runs in O(n²) but you can do it in O(nlogn) by keeping a counter for each letter in the alphabet.

int[] charCount = new int[26];
char[] chars = foog.toLowerCase().toCharArray();

for (char c : chars) {
    charCount[c - 'a']++;
}

Arrays.sort(charCount);
int max = charCount[charCount.length - 1];

Or you can make it even run in O(n) by just looking at the maximum value, you do not even have to sort.

int[] charCount = new int[26];
char[] chars = foog.toLowerCase().toCharArray();

for (char c : chars) {
    charCount[c - 'a']++;
}

int max = Arrays.stream(charCount).max().getAsInt();

Just a suggestion ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM