📜  java, 如何找到重复次数最多的字符 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:14.813000             🧑  作者: Mango

代码示例1
private static String findMaxChar(String str) {
    char[] array = str.toCharArray();
    Set maxChars = new LinkedHashSet();

    int maxCount = 1;
    maxChars.add(array[0]);

    for(int i = 0, j = 0; i < str.length() - 1; i = j){
        int count = 1;
        while (++j < str.length() && array[i] == array[j]) {
            count++;
        }
        if (count > maxCount) {
            maxCount = count;
            maxChars.clear();
            maxChars.add(array[i]);
        } else if (count == maxCount) {
            maxChars.add(array[i]);
        }
    }

    return (maxChars + " = " + maxCount);
}