java - 数组中最大重复字符串
问题描述
问题是
java - 如何仅使用java中数组的操作来获取数组中的最大重复字符串?
所以我在测试中遇到了这个问题并且无法弄清楚。假设我们有一个字符串数组。
str1[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey" }
str2[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey", "caley" }
- 在
str1
abbey中重复次数最多,因此应返回 abbey并 在
str2
abbey和caley中,重复次数相同,因此我们将最大字母表作为获胜者并返回(此处为caley)。c > 一个
所以我试着直到
import java.util.*;
public class test {
static String highestRepeated(String[] str) {
int n = str.length, num = 0;
String temp;
String str2[] = new String[n / 2];
for (int k = 0;k < n; k++) { // outer comparision
for (int l = k + 1; l < n; l++) { // inner comparision
if (str[k].equals(str[l])) {
// if matched, increase count
num++;
}
}
// I'm stuck here
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter how many votes");
int n = sc.nextInt();
String[] str = new String[n];
for (int i = 0; i < n; i++) {
Str[i] = sc.nextLine();
}
String res = highestRepeated(str);
System.out.println(res + " is the winner");
}
}
那么,我应该如何计算每个字符串的出现次数并将其附加到字符串本身。
所有这一切,不使用地图和任何散列,而只是使用数组?
解决方案
这是一个(未抛光的)解决方案:
static String highestRepeated(String[] str) {
String[] sorted = Arrays.copyOf(str, str.length);
Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder());
String currentString = sorted[0];
String bestString = sorted[0];
int maxCount = 1;
int currentCount = 1;
for (int i = 1 ; i < sorted.length ; i++) {
if (currentString.equals(sorted[i])) {
currentCount++;
} else {
if (maxCount < currentCount) {
maxCount = currentCount;
bestString = currentString;
}
currentString = sorted[i];
currentCount = 1;
}
}
if (currentCount > maxCount) {
return currentString;
}
return bestString;
}
解释:
按字典顺序对数组从最高到最低进行排序。就是Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder());
这样。我们按此顺序排序,因为如果有多个重复次数相同的字符串,您需要最大的字符串。
现在我们可以通过遍历数组来计算字符串。我们不需要哈希映射或任何东西,因为我们知道当我们遇到不同的字符串时,数组的其余部分将不再有字符串。
currentString
是我们当前正在计算重复次数的字符串,使用currentCount
. 是我们目前统计maxCount
的重复次数最多的字符串 - - 的出现次数。bestString
if 语句非常不言自明:如果是同一个字符串,则计算它,否则查看我们计算的前一个字符串 ( currentCount
) 出现的次数是否超过当前最大值。
最后,我检查最后一个被计数的字符串是否大于最大值。如果数组中的最后一个字符串恰好是重复次数最多的字符串,bestString
则不会分配给它,因为仅在遇到不同字符串bestString
时才分配。
请注意,此算法不处理空数组或仅一个元素数组等边缘情况。我相信你会自己弄清楚。
推荐阅读
- api - 有谁知道为什么我的云调试器 api 的延迟如此之高?
- c# - IHttpClientFactory 在 .NET Core 3.1 中因套接字异常而间歇性失败
- python - 从 HTML 中获取所有链接、URL 和 URI
- git - 如何无视。vs2019中使用GitHub时的vcxproj文件
- reactjs - CORS 策略已阻止从源“http://localhost:3000”访问“http://127.0.0.1:8000/server/api/auth/login”处的 XMLHttpRequest
- javascript - 在具有辅助功能的 JS 中设置焦点-voiceOver IOS
- python - “charmap”编解码器无法在位置 1 编码字符“\u0110”:字符映射到
使用 pd.read_csv 读取 csv 文件时 - python - JSON到带有嵌套列表的熊猫数据框
- c++ - 如何仅使用 c++ 中超过 2 名教师任期的 getter 来显示数据
- c# - 更改 .Net 5 项目 Sdk 的后果