You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java查找字符串中第二高频字符并满足指定输出规则

Java实现特殊规则下的第二高频字符统计

需求说明

给定任意仅由小写英文字母组成的字符串,统计并输出符合以下规则的第二高频字符组:

  • 此处的「第二高频」指排除所有最高频字符后,剩余字符中的最高出现频率
  • 所有符合第二高频的字符都需要输出,输出顺序按字符在原字符串中首次出现的先后排列,对应示例:
    1. 输入ababababd时,最高频的a、b均出现4次,剩余字符最高频为1次(仅d),输出d
    2. 输入ababababdc时,最高频的a、b均出现4次,剩余字符最高频为1次(d、c),按出现顺序输出dc

当前代码问题

你已经完成了字符频次统计、最高频次计算的基础逻辑,缺少两个核心步骤:

  1. 计算排除最高频次后的第二高频次值
  2. 收集所有频次等于第二高频次的字符,按要求顺序去重输出

修改后完整代码

public class MemorizeWorld {
    public static void main(String[] args) {
        Solution solution = new Solution();
        // 测试用例1 输出d
        String test1 = "ababababd";
        System.out.println(solution.solution(test1));
        // 测试用例2 输出dc
        String test2 = "ababababdc";
        System.out.println(solution.solution(test2));
    }
}

class Solution {
    public String solution(String a) {
        int[] countArray = new int[26];
        char[] charArray = a.toCharArray();

        // 统计每个字符出现次数
        for (char c : charArray) {
            int index = c - 'a';
            countArray[index]++;
        }

        // 计算最高频次max
        int max = 0;
        for (int count : countArray) {
            if (count > max) {
                max = count;
            }
        }

        // 计算第二高频次secondMax:排除所有等于max的频次后取最大值
        int secondMax = 0;
        for (int count : countArray) {
            if (count < max && count > secondMax) {
                secondMax = count;
            }
        }

        // 按原字符串顺序收集符合要求的字符,去重避免重复加入
        StringBuilder result = new StringBuilder();
        boolean[] added = new boolean[26];
        for (char c : charArray) {
            int index = c - 'a';
            if (countArray[index] == secondMax && !added[index]) {
                result.append(c);
                added[index] = true;
            }
        }

        return result.toString();
    }
}

内容的提问来源于stack exchange,提问作者YeonSoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 13:15:02