按出现次数对子字符串进行降序排序 - Java
免得说我有字符串:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
输出:
[BB, CC, AA]
代码:
Output:
[BB, CC, AA]
Code:
你可以做的是这样的(粗略的代码):
然后:
编辑:实际的排序(再次粗略的代码和未经检查):
随意评论。
What you could do is something like this (rough code):
Then:
Edit: The actual sorting (again rough code and unchecked):
Feel free to comment.
如果你想使用番石榴:
If you want to use Guava:
我不确定是否存在用于此确切目的的方法。
但是,您可以使用
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.