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

如何修改Java代码实现n个字符串间重复字符的查找与输出

解决方案:处理n个字符串的公共重复字符

你的当前代码只能固定处理2个字符串的交集,要扩展到支持任意n个字符串并找出所有字符串都包含的公共字符(比如你例子里的CDF是三个字符串共有的),可以按以下思路修改:

核心思路

  • 先获取要处理的字符串总数n
  • 以第一个字符串的去重字符作为初始「公共字符候选集」
  • 逐个读取后续字符串,每个字符串先去重,然后和当前候选集求交集(只保留双方都有的字符)
  • 最终候选集就是所有字符串共有的字符,按需求输出

修改后的完整代码

import java.util.*;

public class CommonChars {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 第一步:输入字符串数量n
        System.out.print("请输入字符串的数量n:");
        int n = scanner.nextInt();
        scanner.nextLine(); // 读取换行符,避免影响后续字符串读取
        
        // 第二步:读取第一个字符串,初始化公共字符候选集(用LinkedHashSet保持字符顺序)
        System.out.print("请输入第1个字符串:");
        String firstStr = scanner.nextLine();
        Set<Character> commonChars = new LinkedHashSet<>();
        for (char c : firstStr.toCharArray()) {
            commonChars.add(c);
        }
        
        // 第三步:遍历剩下的n-1个字符串,逐步缩小公共字符集
        for (int i = 2; i <= n; i++) {
            System.out.print("请输入第" + i + "个字符串:");
            String currentStr = scanner.nextLine();
            // 先对当前字符串去重,得到当前字符串的字符集合
            Set<Character> currentChars = new HashSet<>();
            for (char c : currentStr.toCharArray()) {
                currentChars.add(c);
            }
            
            // 求交集:只保留commonChars中同时存在于currentChars的字符
            Iterator<Character> iterator = commonChars.iterator();
            while (iterator.hasNext()) {
                Character c = iterator.next();
                if (!currentChars.contains(c)) {
                    iterator.remove();
                }
            }
            
            // 如果公共字符集已经为空,提前结束循环
            if (commonChars.isEmpty()) {
                break;
            }
        }
        
        // 第四步:输出结果
        System.out.print("所有字符串的公共字符为:");
        for (char c : commonChars) {
            System.out.print(c);
        }
        
        scanner.close();
    }
}

关键改进点

  • 使用Set优化效率:用LinkedHashSet既可以去重,又能保持字符在第一个字符串中的出现顺序;HashSet的contains方法时间复杂度为O(1),比原代码中String.contains的O(n)高效很多
  • 动态缩小候选集:每处理一个字符串就更新公共字符集,确保始终只保留所有已处理字符串共有的字符
  • 提前终止逻辑:如果中途公共字符集为空,可以直接停止后续处理,避免不必要的计算
  • 支持任意n个字符串:不再局限于固定2个输入,完全适配你需要的n个字符串场景

测试你给出的例子:

输入n=3
第1个字符串:ABCDEF
第2个字符串:BCDEF
第3个字符串:CDFGH
输出:CDF

完全符合你的期望。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 02:12:44