按出现次数对子字符串进行降序排序 - Java

发布于 2024-11-26 22:20:35 字数 223 浏览 2 评论 0原文

免得说我有字符串:

 String test= "AA BB CC BB BB CC BB";

我想做的是创建这样的字符串数组:

 String[]{"BB", "CC", "AA"}

因为 B 出现了 4 次,C 出现了 2 次,A 只出现了 1 次。

这个问题的解决方案是什么样的?

Lest's say I have string:

 String test= "AA BB CC BB BB CC BB";

What I would like to do is create String array like this:

 String[]{"BB", "CC", "AA"}

Since B occurred 4 times C did 2 times and A only 1 time.

What would solution for this problem look like?

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

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

发布评论

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

评论(4

瞎闹 2024-12-03 22:20:35
String test = "AA BB CC BB BB CC BB";
System.out.println(Arrays.deepToString(sort(test)));

输出:[BB, CC, AA]

代码:

public static String[] sort(String test) {
    String[] strings = test.split(" ");
    HashMap<String,Integer> map = new HashMap<String,Integer>();
    for (String s : strings) {
        Integer i = map.get(s);
        if (i != null) {
            map.put(s, i+1);
        } else {
            map.put(s, 1);
        }
    }

    TreeMap<Integer,String> sort = new TreeMap<Integer,String>(Collections.reverseOrder());
    for (Entry<String,Integer> e : map.entrySet()) {
        sort.put(e.getValue(), e.getKey());
    }

    return sort.values().toArray(new String[0]);
}
String test = "AA BB CC BB BB CC BB";
System.out.println(Arrays.deepToString(sort(test)));

Output: [BB, CC, AA]

Code:

public static String[] sort(String test) {
    String[] strings = test.split(" ");
    HashMap<String,Integer> map = new HashMap<String,Integer>();
    for (String s : strings) {
        Integer i = map.get(s);
        if (i != null) {
            map.put(s, i+1);
        } else {
            map.put(s, 1);
        }
    }

    TreeMap<Integer,String> sort = new TreeMap<Integer,String>(Collections.reverseOrder());
    for (Entry<String,Integer> e : map.entrySet()) {
        sort.put(e.getValue(), e.getKey());
    }

    return sort.values().toArray(new String[0]);
}
预谋 2024-12-03 22:20:35

你可以做的是这样的(粗略的代码):

String[] myOccurences = test.split(" ");

然后:

HashMap<String,Integer> occurencesMap = new HashMap<String,Integer>()

for( String s : myOccurences ){
    if( occurencesMap.get( s ) == null ){
        occurencesMap.put(s, 1);
    } else {
        occurencesMap.put(s, occurencesMap.get(s)++ );
    }
}

编辑:实际的排序(再次粗略的代码和未经检查):

List<String> mapKeys = new ArrayList<String>(occurencesMap.keySet()); // Keys
List<Integer> mapValues = new ArrayList<Integer>(occurencesMap.values()); // Values

TreeSet<Integer> sortedSet = new TreeSet( mapValues ); // Sorted according to natural order                
Integer[] sortedValuesArray = sortedSet.toArray();

HashMap<String,Integer> lhMap = new LinkedHashMap<String,Integer>(); // LinkedHashMaps conserve order

for (int i=0; i<size; i++){
    lhMap.put(mapKeys.get(mapValues.indexOf(sortedArray[i])), sortedValuesArray[i]);
}

mapKeys = new ArrayList<String>(occurencesMap.keySet()); // Keys again, this time sorted
Collections.sort(mapKeys, Collections.reverseOrder()); // Reverse since original ascending

String[] occurencesSortedByDescendingArray = mapKeys.toArray();

随意评论。

What you could do is something like this (rough code):

String[] myOccurences = test.split(" ");

Then:

HashMap<String,Integer> occurencesMap = new HashMap<String,Integer>()

for( String s : myOccurences ){
    if( occurencesMap.get( s ) == null ){
        occurencesMap.put(s, 1);
    } else {
        occurencesMap.put(s, occurencesMap.get(s)++ );
    }
}

Edit: The actual sorting (again rough code and unchecked):

List<String> mapKeys = new ArrayList<String>(occurencesMap.keySet()); // Keys
List<Integer> mapValues = new ArrayList<Integer>(occurencesMap.values()); // Values

TreeSet<Integer> sortedSet = new TreeSet( mapValues ); // Sorted according to natural order                
Integer[] sortedValuesArray = sortedSet.toArray();

HashMap<String,Integer> lhMap = new LinkedHashMap<String,Integer>(); // LinkedHashMaps conserve order

for (int i=0; i<size; i++){
    lhMap.put(mapKeys.get(mapValues.indexOf(sortedArray[i])), sortedValuesArray[i]);
}

mapKeys = new ArrayList<String>(occurencesMap.keySet()); // Keys again, this time sorted
Collections.sort(mapKeys, Collections.reverseOrder()); // Reverse since original ascending

String[] occurencesSortedByDescendingArray = mapKeys.toArray();

Feel free to comment.

想你只要分分秒秒 2024-12-03 22:20:35

如果你想使用番石榴:

Lists.transform(
  Ordering
    .natural()
    .onResultOf(new Function<Multiset.Entry<String>, Integer>() {
        public Integer apply(Multiset.Entry<String> entry) {
          return entry.getCount();
        }
      })
    .reverse()
    .sortedCopy(
        ImmutableMultiset.copyOf( Splitter.onPattern("\\s+").split(test) ).entrySet()
      ),
  new Function<Multiset.Entry<String>, String>() {
    public String apply(Multiset.Entry<String> entry) {
      return entry.getElement();
    }
  }
);

If you want to use Guava:

Lists.transform(
  Ordering
    .natural()
    .onResultOf(new Function<Multiset.Entry<String>, Integer>() {
        public Integer apply(Multiset.Entry<String> entry) {
          return entry.getCount();
        }
      })
    .reverse()
    .sortedCopy(
        ImmutableMultiset.copyOf( Splitter.onPattern("\\s+").split(test) ).entrySet()
      ),
  new Function<Multiset.Entry<String>, String>() {
    public String apply(Multiset.Entry<String> entry) {
      return entry.getElement();
    }
  }
);
窝囊感情。 2024-12-03 22:20:35

我不确定是否存在用于此确切目的的方法。

但是,您可以使用 String.split() 方法将单个字符串拆分为字符串数组。从那里,您可以找到唯一的字符串(通过手动检查或将它们全部添加到集合中,这将检查重复项)。每次添加元素但它不属于集合时,都会跟踪(并增加每个唯一字符串唯一的计数器)。然后创建一个根据此计数排序的数组。

映射非常适合保存字符串/计数,因为它将维护唯一字符串集作为键,并将每个字符串的计数作为值。

I am not sure if a method exists for this exact purpose.

However, you could use the String.split() method to split the single string into an array of strings. From there, you could locate unique strings (either by manually checking or adding them all to a set, which would check for duplicates). Track (and increment a counter unique to each unique String) each time you add an element and it is not part of the collection. Then create an array that is sorted based on this count.

A map would be ideal for holding the String/count, as it would maintain the set of unique Strings as keys, and the count for each String as the value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文