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

如何修改代码,从含重复"hello"的数组中仅输出一次最长字符串?

修正方案:找出数组中最长且不重复的字符串

当前代码的问题在于,遇到长度相同的字符串时直接追加到结果中,未做去重处理,导致重复的"hello"被输出多次。以下是两种可行的修正方案:

方案一:利用HashSet自动去重(推荐)

借助HashSet的自动去重特性,逻辑清晰且扩展性强:

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

public class Main {
    public static void main(String[] args) {
        String[] massive = {"hello", "hello", "ola", "bye", "ciao"};
        int maxLength = 0;
        Set<String> longestUniqueStrings = new HashSet<>();

        // 遍历数组,确定最长字符串长度并收集不重复的最长字符串
        for (String str : massive) {
            int currentLen = str.length();
            if (currentLen > maxLength) {
                maxLength = currentLen;
                longestUniqueStrings.clear();
                longestUniqueStrings.add(str);
            } else if (currentLen == maxLength) {
                longestUniqueStrings.add(str);
            }
        }

        // 格式化输出结果
        System.out.println(String.join(", ", longestUniqueStrings));
    }
}

方案优势

  • 集合自动过滤重复项,无需手动编写重复判断逻辑
  • 分阶段处理逻辑更清晰:先确定最长长度,再收集符合条件的字符串
  • 适配多种场景,比如数组中存在多个不同的最长字符串时,也能正确去重输出

方案二:手动判断去重

如果不想引入集合类,可以通过StringBuilder构建结果时手动检查是否已包含当前字符串:

public class Main {
    public static void main(String[] args) {
        String[] massive = {"hello", "hello", "ola", "bye", "ciao"};
        String longestString = "";
        StringBuilder maxString = new StringBuilder();

        for (String string : massive) {
            if (string.length() > longestString.length()) {
                longestString = string;
                maxString.setLength(0);
                maxString.append(string);
            } else if (string.length() == longestString.length()) {
                // 检查当前字符串是否已在结果中,未包含则追加
                if (maxString.indexOf(string) == -1) {
                    if (maxString.length() != 0) {
                        maxString.append(", ");
                    }
                    maxString.append(string);
                }
            }
        }
        System.out.println(maxString);
    }
}

方案说明

  • 使用StringBuilder提升字符串拼接效率
  • 通过indexOf方法判断字符串是否已存在,避免重复添加

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 12:15:20