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

获取最大Anagram组方法在无变位词小数组上执行失败,请求协助

问题诊断与修复

核心问题

你的代码在处理无变位词的输入数组时(所有单词彼此都不是变位词,每个组的大小都是1),错误返回了包含单个单词的数组,不符合需求中“无变位词时返回空数组”的要求。根源在于代码未判断最大变位词组的大小是否大于1——只有当存在至少两个互为变位词的单词时,才需要返回对应组,否则应返回空数组。

具体问题点

  1. 当所有组大小均为1时,largestNumber的值为1,代码直接创建长度为1的数组返回,违反需求规则。
  2. 额外隐患:temp.indexOf(largestNumber)会返回第一个匹配的索引,若存在多个相同大小的最大组(如多个大小为1的组),会错误选取第一个组的标识,但这并非无变位词场景下的核心问题。

修复后的代码

/**
 * @param largestStr a string array.
 * @return the largest group of anagrams in the input array of words, in no
 *         particular order. It returns an empty array if there are no anagrams
 *         in the input array.
 */
public static String[] getLargestAnagramGroup(String[] largestStr) {
    if (largestStr.length == 0) {
        return largestStr;
    }

    // 创建副本数组用于生成变位词统一标识
    String[] duplicate = new String[largestStr.length];
    for (int i = 0; i < duplicate.length; i++) {
        duplicate[i] = largestStr[i];
    }

    // 将每个单词转小写并排序,生成变位词的唯一标识
    for (int i = 0; i < duplicate.length; i++) {
        duplicate[i] = (String) sort(duplicate[i].toLowerCase());
    }

    // 用Lambda表达式实现Comparator,替代内部类
    insertionSort(duplicate, (o1, o2) -> o1.compareTo(o2));

    // 统计每个变位词组的大小
    ArrayList<Integer> groupSizes = new ArrayList<>();
    String currentKey = duplicate[0];
    int currentCount = 0;

    for (String key : duplicate) {
        if (key.equals(currentKey)) {
            currentCount++;
        } else {
            groupSizes.add(currentCount);
            currentKey = key;
            currentCount = 1;
        }
    }
    groupSizes.add(currentCount);

    // 找到最大的组大小
    int maxGroupSize = 0;
    for (int size : groupSizes) {
        if (size > maxGroupSize) {
            maxGroupSize = size;
        }
    }

    // 关键判断:最大组大小<=1时,说明无变位词,返回空数组
    if (maxGroupSize <= 1) {
        return new String[0];
    }

    // 定位最大组对应的变位词标识
    int sum = 0;
    for (int i = 0; i < groupSizes.size(); i++) {
        if (groupSizes.get(i) == maxGroupSize) {
            break;
        }
        sum += groupSizes.get(i);
    }
    String targetKey = duplicate[sum];

    // 收集原数组中属于该变位词组的所有单词
    String[] result = new String[maxGroupSize];
    int count = 0;
    for (String word : largestStr) {
        if (areAnagrams(word, targetKey)) {
            result[count++] = word;
        }
    }

    return result;
}

修复说明

  1. 新增核心判断逻辑:在获取最大组大小后,判断其是否小于等于1,若是则直接返回空数组,严格符合需求。
  2. 简化Comparator实现:用Lambda表达式替代内部类,代码更简洁且满足题目要求。
  3. 优化变量命名:将temp改为groupSizes、totalValues改为currentCount,提升代码可读性。
  4. 修正目标标识定位:原代码中sum - 1可能导致索引错误,改为累加找到目标组的起始索引,直接取duplicate[sum]更准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:15:42