查找字符串中出现次数最多的字符? [英] Find character with most occurrences in string?
本文介绍了查找字符串中出现次数最多的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有一个字符串:
For example, I have a string:
"abbbbccd"
b
出现次数最多.使用C ++时,处理此问题的最简单方法是将每个字符插入map<>
中.我必须在C#中做同样的事情吗?有没有一种使用LINQ做到这一点的优雅方法?
b
has the most occurrences. When using C++, the easiest way to handle this is inserting each character into a map<>
. Do I have to do the same thing in C#? Is there an elegant way to do it using LINQ?
推荐答案
input.GroupBy(x => x).OrderByDescending(x => x.Count()).First().Key
注意:
- 如果您需要此代码才能在.Net的古代(2.0)版本上工作,请考虑 LinqBridge .如果您不能使用C#3.0(以.Net 2.0为目标),则可能会缺少lambda支持,因此最好使用其他解决方案. xanatos答案涵盖了另一个.Net 2.0+选项.
- 对于
"aaaabbbb"
而言,将仅返回其中之一(感谢 xanatos 进行评论).如果您需要所有具有最大数量的元素,请使用 Albin解决方案. - 由于对此解决方案进行了排序(如果为O(n log n)解决方案).如果您需要的更好-通过线性搜索找到最大值,而不是先排序即可得到O(n).参见 LINQ:如何对集合中所有对象的属性执行.Max()并返回具有最大值的对象
- if you need this to work on ancient (2.0) versions of .Net consider LinqBridge. If you can't use C# 3.0 (targeting .Net 2.0) you probably better off with other solutions due to missing lambda support. Another .Net 2.0+ option is covered in xanatos answer.
- for the case of
"aaaabbbb"
only one of those will be returned (thanks xanatos for comment). If you need all of the elements with maximum count, use Albin's solution instead. - due to sorting this if O(n log n) solution. If you need better than that - find Max value by linear search instead of sorting first which will give O(n). See LINQ: How to perform .Max() on a property of all objects in a collection and return the object with maximum value
这篇关于查找字符串中出现次数最多的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文