簡體   English   中英

需要找到字符串中最頻繁出現的字符並返回出現的次數

[英]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;
}

返回5就是這樣,它可以工作,然后當它返回時,我將返回max,但是現在我必須打印它。

現在我很確定自己搞砸了很多事情。 但是我認為它們的最高編號仍會保留到最后,並且通過對數組進行排序,我可以檢索出最頻繁出現的字符的次數。

對於字符串,我使用“ habakkuk”,並且由於有3 k,我希望打印“ 3”,但沒有。 誰能告訴我我在做什么錯? 謝謝!

你只有一個小錯字

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

應該

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

旁注:您可以改善算法。 現在,它以O(n²)運行,但是您可以通過為字母中的每個字母保留一個計數器來在O(nlogn)中進行操作。

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];

或者,您甚至可以通過查看最大值來使其甚至在O(n)中運行,您甚至不必進行排序。

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

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

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

只是一個建議;-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM