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

如何获取数组中出现次数最多的相邻变位词组及对应索引

解决已排序变位数组中出现次数最多的变位词组问题

Hey there! Let's fix up your code to find the largest anagram group in that sorted array. First, let's go over the issues with your current implementation, then walk through the corrected version.

现有代码的问题分析

Your current code has a few key gaps:

  • The loop logic skips elements incorrectly with i = j, and doesn't track the size or content of anagram groups
  • There's no logic to record the largest group found, so it just returns null
  • The main method has syntax errors: missing semicolon after array initialization, and unnecessary String[] type declaration when calling the method

修正后的完整代码

Here's the fully working version, including a helper AnagramUtil implementation (if you already have this class, you can skip that part):

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// Helper class for anagram checks (skip if you already have this)
class AnagramUtil {
    // Check if two strings are anagrams
    public static boolean areAnagrams(String s1, String s2) {
        if (s1.length() != s2.length()) return false;
        
        char[] arr1 = s1.toCharArray();
        char[] arr2 = s2.toCharArray();
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        
        return Arrays.equals(arr1, arr2);
    }

    // Find the largest anagram group in a sorted adjacent anagram array
    public static String[] getLargestAnagramGroup(String[] stringList) {
        // Handle edge cases: empty or null input
        if (stringList == null || stringList.length == 0) {
            return new String[0];
        }

        List<String> maxGroup = new ArrayList<>();
        List<String> currentGroup = new ArrayList<>();
        currentGroup.add(stringList[0]);

        // Traverse from the second element onward
        for (int i = 1; i < stringList.length; i++) {
            // Since array is sorted by adjacent anagrams, compare with current group's first element
            if (areAnagrams(stringList[i], currentGroup.get(0))) {
                currentGroup.add(stringList[i]);
            } else {
                // Update max group if current group is larger
                if (currentGroup.size() > maxGroup.size()) {
                    maxGroup = new ArrayList<>(currentGroup);
                }
                // Reset current group for the new non-anagram element
                currentGroup.clear();
                currentGroup.add(stringList[i]);
            }
        }

        // Check the last group after loop ends
        if (currentGroup.size() > maxGroup.size()) {
            maxGroup = currentGroup;
        }

        // Convert List to String array and return
        return maxGroup.toArray(new String[0]);
    }

    public static void main(String[] args) {
        String[] listOfSortedAnagrams = new String[] {"asp", "pas", "code", "coed", "deco", "France"};
        String[] largestGroup = getLargestAnagramGroup(listOfSortedAnagrams);
        System.out.print("Most occurring anagrams are: " + String.join(", ", largestGroup));
    }
}

代码逻辑解释

  • Edge case handling: First checks for empty or null input to avoid runtime errors
  • Group tracking: Uses two ArrayLists to keep track of the current anagram group being built, and the largest group found so far
  • Efficient comparison: Since the array is already sorted with adjacent anagrams, we only need to compare each element to the first element of the current group
  • Final group check: After the loop ends, we have to compare the last group to ensure we don't miss it
  • Clean output: Uses String.join to format the result into a readable string

预期输出

When you run this code, you'll get exactly the result you want:

Most occurring anagrams are: code, coed, deco

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:03:28