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

Java中对比字符串数组与字符数组筛选符合字符次数要求的去重结果

代码调整方案

原代码问题

  • 直接将完整字符串与单个字符做相等判断,逻辑不成立,无法匹配到符合要求的内容
  • 没有做字符出现次数的统计校验,不满足规则①的频次要求
  • 没有去重逻辑,重复的符合要求字符串会多次输出,不符合规则②

实现逻辑

  1. 先统计字符数组中各字符的出现频次,存入计数容器
  2. 遍历字典数组时通过Set容器做去重,已经输出过的字符串不再重复处理
  3. 对每个未处理过的字符串,统计其内部各字符的出现频次,与字符数组的频次逐一对比,所有字符的频次都不超过字符数组的对应值时,判定为符合要求

调整后代码(基于char类型字符数组实现)

import java.util.HashSet;
import java.util.Set;

public class WordMatch {
    public static void main(String[] args) {
        String[] dictionaryArr= new String[]{"mee","go","bat","me","eat","goal","boy","run","go"};
        char[] characterArr={'e','o','b','a','m','g','l'};
        
        // 统计字符数组的字符频次,示例均为小写字母,用数组计数效率更高
        int[] charCount = new int[26];
        for (char c : characterArr) {
            charCount[c - 'a']++;
        }
        
        // 去重用Set
        Set<String> existed = new HashSet<>();
        for (String word : dictionaryArr) {
            // 已输出过的直接跳过
            if (existed.contains(word)) {
                continue;
            }
            // 复制一份频次计数,避免修改原数据影响后续单词校验
            int[] tempCount = charCount.clone();
            boolean match = true;
            for (char c : word.toCharArray()) {
                int index = c - 'a';
                tempCount[index]--;
                // 频次不足直接标记不匹配,跳出循环
                if (tempCount[index] < 0) {
                    match = false;
                    break;
                }
            }
            if (match) {
                System.out.println(word);
                existed.add(word);
            }
        }
    }
}

运行结果

go
me
goal

完全符合预期输出要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:54:04