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

Java 如何从字符串中找出出现次数最多的数字?,java,string,frequency,Java,String,Frequency,我有一个字符串,其中包含逗号分隔形式的数字。我想从字符串中提取出现次数最多的数字。 例如,我有一个字符串,如 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 如果所有数字都是唯一的,那么我需要第一个 建议我使用更好的方法。我将使用一个整数映射数组来计算每个数字,并使用变量来存储计数最高的数字 将字符串拆分为数字列表,并在列表

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

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

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


建议我使用更好的方法。

我将使用一个整数映射数组来计算每个数字,并使用变量来存储计数最高的数字

将字符串拆分为数字列表,并在列表上循环

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


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

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

计数:


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

假设这是一个家庭作业,我将提出一个没有代码的大致想法:

  • 首先拆分
    ,“
    字符上的字符串
  • 创建一个带有计数的
    Integer
    Integer
    的初始空映射
  • 检查从拆分中得到的部分,并将它们解析为
    int
  • 对于每个值,查看地图中是否有相应的项目;如果有一个数字,增加它;否则,添加带有新编号和
    1
    的条目
  • 完成标记后,浏览地图并找到最大值
  • 如果最大值为
    1
    ,则返回第一个令牌
  • 如果最大值不是
    1
    ,请再次浏览地图,并收集值等于最大值的所有键

这种方法允许您处理非常大的数字,并且不会区分带前导零的数字和不带前导零的数字。换句话说,它会将
1,2,03,3,3,2
序列中的
3
识别为唯一的赢家,而不是将字符串转换为数字列表

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

对数字列表进行排序

迭代列表并保持

  • 当前编号的出现次数
  • 数字的当前最大出现次数
  • 您遇到的不同数字的数量
  • 出现次数较多的一组数字等于最大值
在每次迭代中,如果当前数字等于当前最大值,则将当前数字添加到结果中。如果大于当前最大值,请清除结果集并将当前数字添加到结果中

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

请尝试下面的代码

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);
    }
}    
如果有任何疑问,请告诉我

干杯

这里有一个使用and的解决方案

大纲:

  • 将字符串拆分为单词列表
  • 计算每个单词的频率并创建一张地图
    word->Count
  • 反转以创建多重映射
    Count->Words
  • 转换为已排序的NavigableMap
  • 获取计数最高的单词
  • 返回计数最高的单词
  • 代码:

    公共类最高级计数器查找器{
    公共静态ImmutableSet findWordsWithGreatestCount(字符串字字符串){
    列出单词=拆分(单词字符串,“,”);
    映射单词计数=toMapWithCounts(单词);
    Multimap countsToWords=toInverseMultimap(wordsToCounts);
    NavigableMap countsToWordsSorted=toNavigableMap(countsToWords);
    集合字的最高计数=最后一个值(CountStowOrdstorted);
    返回ImmutableSet.copyOf(wordsWithHighestCount);
    }
    公共静态不可变列表拆分(字符串字字符串、字符串分隔符){
    Iterable parts=Splitter.on(分隔符).split(字字符串);
    返回不可变列表。副本(部分);
    }
    公共静态ImmutableMap toMapWithCounts(Iterable条目){
    Multiset entriesWithCounts=HashMultiset.create(条目);
    返回toMap(entriesWithCounts);
    }
    公共静态不可变映射toMap(多集多集){
    ImmutableMap.Builder immutableMapBuilder=ImmutableMap.Builder();
    for(Multiset.Entry:Multiset.entrySet()){
    immutableMapBuilder.put(entry.getElement(),entry.getCount());
    }
    返回immutableMapBuilder.build();
    }
    公共静态ImmutableMultimap到InverseMultiMap(映射映射){
    Multimap Multimap=Multimap.forMap(map);
    返回ImmutableMultimap.copyOf(multimap.inverse();
    }
    公共静态导航地图toNavigableMap(多重地图多重地图){
    返回新的树映射(multimap.asMap());
    }
    
    public static V lastValue(NavigableMaps)查找数字需要一些时间,因为str有很多数字。首先,我不会使用字符串,因为将其转换为数字可能需要比搜索更长的时间。我个人建议使用
    java.util.Scanner
    “\\s*,\\s*”
    作为分隔符,使用方法
    nextInt
    检索整数。
    Input is : 1,2,3,4,5,6,2,3,4,1,4,33,33,33
    Result is 1,2,3,4,33,
    
    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();
        }
    }