首页 > 解决方案 > 数组中最大重复字符串

问题描述

问题是

java - 如何仅使用java中数组的操作来获取数组中的最大重复字符串?

所以我在测试中遇到了这个问题并且无法弄清楚。假设我们有一个字符串数组。

str1[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey" }
str2[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey", "caley" }
  1. str1 abbey中重复次数最多,因此应返回 abbey并
  2. str2 abbeycaley中,重复次数相同,因此我们将最大字母表作为获胜者并返回(此处为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");
    }
}

那么,我应该如何计算每个字符串的出现次数并将其附加到字符串本身。

所有这一切,不使用地图和任何散列,而只是使用数组?

标签: javaarraysmax

解决方案


这是一个(未抛光的)解决方案:

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时才分配。

请注意,此算法不处理空数组或仅一个元素数组等边缘情况。我相信你会自己弄清楚。


推荐阅读