请勿使用数组的java字符串中出现最大字符数

时间:2018-06-03 00:25:12

标签: java

我需要在java中查找字符串中字符的最大出现次数,但是如果有多个字符出现多次。它将打印出第一个字符。例如,如果我尝试aabbb它将打印:2而不是b:3。我不知道如何使用数组。请给我建议。

    int count = 1;
    int max = 1;
    String newstring = "";
    String currentletter = "";
    String finalletter = "";
    for (int i = 0; i < word.length() - 1; i++) {
        currentletter = word.substring(i, i+1);
        if (newstring.contains(currentletter)) {
            currentletter = "";
        } else {
            newstring += currentletter;
            for (int j = i+1; j < word.length(); j++) {
                if (currentletter.equals(word.substring(j, j+1))) {
                    count++;
                    finalletter = currentletter;
                }
            }
            if (count > max) {
                max = count;
                count = 0;
                currentletter = "";
                System.out.print(finalletter + ": ");
            }
        }
    }
    System.out.println(max + " ");
}

1 个答案:

答案 0 :(得分:1)

我会使用Map<Character, Integer>两个循环。首先,通过迭代map并计算字母的出现次数来填充String。其次,迭代Map条目集并将其与局部最大值进行比较。最后,显示结果(或显示无结果的消息)。像,

String s = "aabbb";
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
    char ch = s.charAt(i);
    map.put(ch, 1 + map.getOrDefault(ch, 0));
}
Map.Entry<Character, Integer> max = null;
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
    if (max == null || max.getValue() < entry.getValue()) {
        max = entry;
    }
}
if (max != null) {
    System.out.printf("%c: %d%n", max.getKey(), max.getValue());
} else {
    System.out.println("no result");
}

我得到了

b: 3