如何查找字符串数组中出现次数最多的元素,适配现有整数数组实现逻辑?
字符串数组最高频元素适配方案
原有逻辑仅需修改3处核心点即可适配字符串场景:
- 入参数组类型从
int[]改为String[] - 存储最高频元素、临时遍历元素的变量类型从
int改为String - 数值比较的
==运算符替换为equals()方法,Java中==对字符串是比较内存地址,equals()才是比较实际内容
调整后完整代码如下:
// 可提前加判空逻辑避免异常 if (a == null || a.length == 0) { return null; } int count = 1, tempCount; String popular = a[0]; String temp; for (int i = 0; i < (a.length - 1); i++) { temp = a[i]; tempCount = 0; for (int j = 1; j < a.length; j++) { if (temp.equals(a[j])) { tempCount++; } } if (tempCount > count) { popular = temp; count = tempCount; } } return popular;
补充说明:你示例中的数组声明写法有误,正确的字符串数组声明应为
String[] a = {"Sparky", "Mary", "Sparky", "John", "Betsy"},传入上述代码即可正确返回最高频元素Sparky。如果存在多个频率相同的最高频元素,代码会返回第一个出现的元素,和原有整数数组逻辑保持一致。
内容的提问来源于stack exchange,提问作者Jonathan
相关产品推荐
相关产品推荐

