Java中仅通过数组操作获取数组内重复次数最多的字符串
仅用数组操作找出Java字符串数组中重复次数最多的元素
这题我之前也碰到过,不用集合类只靠数组确实有点绕,不过拆解成几步就清晰了,我给你捋捋思路和具体实现:
核心思路
因为不能用HashMap这类方便统计的集合,咱们只能靠数组来完成统计、找最大值、去重这几个关键步骤:
- 第一步:统计每个字符串在数组中的出现次数,用一个int数组和原数组一一对应
- 第二步:找出所有次数里的最大值
- 第三步:收集所有出现次数等于最大值的字符串,同时要去重(避免同一个字符串多次出现在结果里)
- 第四步:根据结果数量判断是唯一最多还是并列情况,输出对应信息
具体代码实现
public class MostFrequentString { public static void main(String[] args) { String[] str1 = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey" }; String[] str2 = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey", "caley" }; findMostFrequent(str1); findMostFrequent(str2); } private static void findMostFrequent(String[] arr) { if (arr == null || arr.length == 0) { System.out.println("数组为空或null"); return; } // 1. 统计每个元素的出现次数 int[] counts = new int[arr.length]; for (int i = 0; i < arr.length; i++) { int count = 0; for (int j = 0; j < arr.length; j++) { if (arr[i].equals(arr[j])) { count++; } } counts[i] = count; } // 2. 找出最大的出现次数 int maxCount = counts[0]; for (int count : counts) { if (count > maxCount) { maxCount = count; } } // 3. 收集所有次数等于最大值的元素,同时去重 String[] resultCandidates = new String[arr.length]; int candidateIndex = 0; boolean[] isAdded = new boolean[arr.length]; // 标记元素是否已加入结果,避免重复 for (int i = 0; i < arr.length; i++) { if (counts[i] == maxCount && !isAdded[i]) { resultCandidates[candidateIndex++] = arr[i]; // 把所有和当前元素相同的位置都标记为已添加,防止重复加入 for (int j = 0; j < arr.length; j++) { if (arr[i].equals(arr[j])) { isAdded[j] = true; } } } } // 整理结果,去掉数组中多余的null值 String[] finalResult = new String[candidateIndex]; System.arraycopy(resultCandidates, 0, finalResult, 0, candidateIndex); // 4. 输出结果 if (finalResult.length == 1) { System.out.printf("重复次数最多的字符串是:%s,共出现%d次%n", finalResult[0], maxCount); } else { System.out.printf("有%d个字符串重复次数并列最多(均为%d次):", finalResult.length, maxCount); for (int i = 0; i < finalResult.length; i++) { if (i > 0) { System.out.print("、"); } System.out.print(finalResult[i]); } System.out.println(); } } }
代码解释
- 统计次数:用双层循环遍历原数组,每个元素和数组中所有元素比较,统计出现次数后存入
counts数组,索引和原数组一一对应。虽然时间复杂度是O(n²),但完全符合仅用数组操作的要求。 - 找最大次数:遍历
counts数组,记录下最大的次数值maxCount。 - 去重收集候选:用
isAdded数组标记已经加入结果的元素,避免同一个字符串被多次收集。比如当我们把"abbey"加入候选后,所有原数组中"abbey"的位置都会被标记为已添加,后续就不会再处理了。 - 结果输出:根据最终结果数组的长度,判断是唯一最多还是并列情况,给出清晰的输出信息。
测试结果
运行上面的代码,针对你给出的两个数组会输出:
重复次数最多的字符串是:abbey,共出现3次
有2个字符串重复次数并列最多(均为3次):abbey、caley
这样就完美解决了你遇到的问题,不管是唯一最多还是并列的情况都能处理到。
内容的提问来源于stack exchange,提问作者nikhil2000
相关产品推荐
相关产品推荐

