如何从字符串中找出出现次数最多的数字?

发布于 2024-12-27 18:30:13 字数 324 浏览 0 评论 0原文

我有一个 String ,其中包含以逗号分隔的形式的数字。我想从字符串中提取出现次数最多的数字。 例如,我有一个字符串,

String str="1,2,3,4,5,6,7,19,18,4";

例如上面的 str,我需要 4,因为 4 是 str 的两倍。

相同

String str2="1,2,3,4,6,4,3,9";

与上面的 str2

,我需要 3,4如果所有数字都是唯一的,那么我需要第一个。

建议我更好的方法。

I have a String which contains numbers in a comma separated form. and I want to extract the most appears numbers from the String.
For example I have a String like..

String str="1,2,3,4,5,6,7,19,18,4";

from the above str i need 4 because 4 is two times in str.

same as

String str2="1,2,3,4,6,4,3,9";

from the above str2 i need 3,4

In case of all numbers are unique then i need first one.

suggest me better approach.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

沧笙踏歌 2025-01-03 18:30:13

您可以使用 java.util.StringTokenizer 使用 , 作为分隔符来标记字符串,然后使用 String.trim( 从每个标记中去除前导和尾随空格),然后使用 Integer.parseInt() 函数将它们存储到 int 数组中。然后你就可以轻松地数出它们了。

用于计数:

如果您的数字范围较小,那么您可以简单地创建一个计数器数组并使用每个数字作为该数组的索引。如果没有,那么您可以使用 HashMap 或类似的东西。

You can tokenize the string using java.util.StringTokenizer using , as the separator, then strip off the leading and trailing spaces from each token using String.trim(), then store them into an array of ints using Integer.parseInt() function. Then you can count them easily.

For counting:

If you have a small range of numbers, then you can simply create a counter array and use each number as an index to that array. If not, then you can use HashMap or something like that.

贱人配狗天长地久 2025-01-03 18:30:13

假设这是一项作业,我将建议一个没有代码的一般想法:

  • 首先在 ',' 字符上拆分字符串
  • 创建一个 Integer 的初始空映射将计数转换为 Integer
  • 遍历从拆分中返回的部分,并将它们解析为 int
  • 对于每个值,查看在地图;如果那里有数字,则增加它;否则,添加包含新编号和 1 的条目。
  • 完成令牌后,遍历地图并找到最大值
  • 如果最大值为 1,则返回第一个令牌
  • 如果最大值不是 1,则转到再次遍历映射,并收集值等于 max 的所有键。

这种方法可以让您处理非常大的数字,并且它不会区分带或不带前导零的数字。换句话说,它将把 1,2,03,3,3,2 序列中的 3 识别为唯一的获胜者,而不是与 2< /代码>。

Assuming that this is a homework, I'll suggest a general idea without the code:

  • Start by splitting the string on the ',' characters
  • Create an initially empty map of Integer to Integer with the counts
  • Go through the parts you've got back from the split, and parse them as int values
  • For each value, see if there is a corresponding item in the map; if there is a number there, increment it; otherwise, add an entry with the new number and 1.
  • Once you're done with the tokens, go through the map and find the max value
  • If the max is 1, return the first token
  • If the max is not 1, go through the map again, and collect all keys where the value is equal to max

This approach lets you work with very large numbers, and it does not discriminate between numbers with and without leading zeros. In other words, it will identify 3 in 1,2,03,3,3,2 sequence as a unique winner, not as a tie with 2.

腻橙味 2025-01-03 18:30:13

我将有一个整数映射数组来计算每个数字,以及一个变量来存储具有最高计数的数字。

将字符串拆分为数字列表,然后循环该列表。

每次查看新数字时,都会增加其在地图中的计数器,如果该计数大于当前最高计数,则将当前最高计数更改为当前计数。在字符串末尾,返回当前最高值。

请注意,如果您还存储第二大计数的数字,则可以通过提前退出循环来进行稍微优化,此时没有足够的数字允许第二大计数超过最高计数。

I would have an array of map of integers to count each number, and variable to store the number with the highest count.

Split the string into a list of numbers, and loop over the list.

Each time you look at a new number, increment its counter in the map, and if that count is greater than the current highest count, change the current highest to the current. At the end of the string, return the current highest.

Note that, if you also store the number with the second biggest count, you can optimise slightly by exiting the loop early, when there are not enough numbers left to allow the second highest count to exceed the highest.

或十年 2025-01-03 18:30:13

将字符串转换为数字列表。

记住列表的第一个数字是什么。

对数字列表进行排序。

迭代列表并保留

  • 当前数字出现的次数。
  • 某个数字的当前最大出现次数
  • 您遇到的不同数字的数量
  • 出现次数等于最大值的数字集

在每次迭代中,如果当前数字等于当前最大值,则将当前数字添加到结果。如果大于当前最大值,则清除结果集并将当前数字添加到结果中。

在循环结束时,如果结果集的大小等于不同数字的数量,则返回对列表进行排序之前记住的第一个数字。

Transform your String into a list of numbers.

Remember what the first number of the list is.

Sort the list of numbers.

Iterate over the list and keep

  • the number of occurrences of the current number.
  • the current max number of occurrences of a number
  • the number of distinct numbers you met
  • the set of numbers that have a number of occurrences equals to the max

At each iteration, if the current number is equal to the current max, add the current number to the result. If it's greater than the current max, clear the set of results and add the current number to the results.

At the end of the loop, if the size of the result set is equal to the number of distinct numbers, return the first number you remembered before sorting the list.

荆棘i 2025-01-03 18:30:13

尝试下面的代码

public class StringCheck {
    public static void main(String args[]) {
        String input = "1,2,3,4,5,6,2,3,4,1,4,33,33,33";
        String result = "";
        String[] arr1 = input.split(",");

        System.out.println("Input is : " + input);

        for (int i = 0; i < arr1.length; i++) {
            int k = 0;
            for (int j = 0; j < arr1.length; j++) {
                if (arr1[i].equals(arr1[j])) {
                    k++;
                    if (k == 2) {
                        if (result.contains(arr1[i])) {
                            break;
                        }
                        result = result + arr1[i] + ",";
                        break;
                    }
                }
            }
        }

        System.out.println("Result is " + result);
    }
}    

下面将输出

Input is : 1,2,3,4,5,6,2,3,4,1,4,33,33,33
Result is 1,2,3,4,33,

如果有任何疑问请告诉我......

干杯!

Try Below Code

public class StringCheck {
    public static void main(String args[]) {
        String input = "1,2,3,4,5,6,2,3,4,1,4,33,33,33";
        String result = "";
        String[] arr1 = input.split(",");

        System.out.println("Input is : " + input);

        for (int i = 0; i < arr1.length; i++) {
            int k = 0;
            for (int j = 0; j < arr1.length; j++) {
                if (arr1[i].equals(arr1[j])) {
                    k++;
                    if (k == 2) {
                        if (result.contains(arr1[i])) {
                            break;
                        }
                        result = result + arr1[i] + ",";
                        break;
                    }
                }
            }
        }

        System.out.println("Result is " + result);
    }
}    

Below will be output

Input is : 1,2,3,4,5,6,2,3,4,1,4,33,33,33
Result is 1,2,3,4,33,

Let me know if there are any queries...

Cheers!!!

空城之時有危險 2025-01-03 18:30:13

这是使用 java.util 的解决方案和 番石榴收集

大纲:

  1. 将字符串拆分为单词列表
  2. 计算每个单词的频率并创建一个映射 Word -> Count
  3. 反转以创建 Multimap Count -> Words
  4. 转换为排序的 NavigableMap
  5. 获取计数最高的单词
  6. 返回计数最高的单词

代码:

public class HighestCountFinder {


    public static ImmutableSet<String> findWordsWithGreatestCount(String wordsString) {
        List<String> words = split(wordsString, ",");

        Map<String, Integer> wordsToCounts = toMapWithCounts(words);

        Multimap<Integer, String> countsToWords = toInverseMultimap(wordsToCounts);

        NavigableMap<Integer, Collection<String>> countsToWordsSorted = toNavigableMap(countsToWords);

        Collection<String> wordsWithHighestCount = lastValue(countsToWordsSorted);

        return ImmutableSet.copyOf(wordsWithHighestCount);
    }


    public static ImmutableList<String> split(String wordsString, String separator) {
        Iterable<String> parts = Splitter.on(separator).split(wordsString);
        return ImmutableList.copyOf(parts);
    }


    public static ImmutableMap<String, Integer> toMapWithCounts(Iterable<String> entries) {
        Multiset<String> entriesWithCounts = HashMultiset.create(entries);
        return toMap(entriesWithCounts);
    }


    public static <E> ImmutableMap<E, Integer> toMap(Multiset<E> multiset) {
        ImmutableMap.Builder<E, Integer> immutableMapBuilder = ImmutableMap.builder();
        for (Multiset.Entry<E> entry : multiset.entrySet()) {
            immutableMapBuilder.put(entry.getElement(), entry.getCount());
        }
        return immutableMapBuilder.build();
    }


    public static <K, V> ImmutableMultimap<V, K> toInverseMultimap(Map<K, V> map) {
        Multimap<K, V> multimap = Multimaps.forMap(map);
        return ImmutableMultimap.copyOf(multimap).inverse();
    }


    public static <K, V> NavigableMap<K, Collection<V>> toNavigableMap(Multimap<K, V> multimap) {
        return new TreeMap<>(multimap.asMap());
    }


    public static <V> V lastValue(NavigableMap<?, V> navigableMap) {
        return navigableMap.lastEntry().getValue();
    }
}

Here's a solution using java.util and Guava collect.

Outline:

  1. Split String into list of words
  2. Count the frequency of each word and create a map Word -> Count
  3. Invert to create a Multimap Count -> Words
  4. Convert to a sorted NavigableMap
  5. Get Words with highest count
  6. Return Words with hightest count

Code:

public class HighestCountFinder {


    public static ImmutableSet<String> findWordsWithGreatestCount(String wordsString) {
        List<String> words = split(wordsString, ",");

        Map<String, Integer> wordsToCounts = toMapWithCounts(words);

        Multimap<Integer, String> countsToWords = toInverseMultimap(wordsToCounts);

        NavigableMap<Integer, Collection<String>> countsToWordsSorted = toNavigableMap(countsToWords);

        Collection<String> wordsWithHighestCount = lastValue(countsToWordsSorted);

        return ImmutableSet.copyOf(wordsWithHighestCount);
    }


    public static ImmutableList<String> split(String wordsString, String separator) {
        Iterable<String> parts = Splitter.on(separator).split(wordsString);
        return ImmutableList.copyOf(parts);
    }


    public static ImmutableMap<String, Integer> toMapWithCounts(Iterable<String> entries) {
        Multiset<String> entriesWithCounts = HashMultiset.create(entries);
        return toMap(entriesWithCounts);
    }


    public static <E> ImmutableMap<E, Integer> toMap(Multiset<E> multiset) {
        ImmutableMap.Builder<E, Integer> immutableMapBuilder = ImmutableMap.builder();
        for (Multiset.Entry<E> entry : multiset.entrySet()) {
            immutableMapBuilder.put(entry.getElement(), entry.getCount());
        }
        return immutableMapBuilder.build();
    }


    public static <K, V> ImmutableMultimap<V, K> toInverseMultimap(Map<K, V> map) {
        Multimap<K, V> multimap = Multimaps.forMap(map);
        return ImmutableMultimap.copyOf(multimap).inverse();
    }


    public static <K, V> NavigableMap<K, Collection<V>> toNavigableMap(Multimap<K, V> multimap) {
        return new TreeMap<>(multimap.asMap());
    }


    public static <V> V lastValue(NavigableMap<?, V> navigableMap) {
        return navigableMap.lastEntry().getValue();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文