查找字符串中出现次数最多的字符?
例如,我有一个字符串:
"abbbbccd"
b
出现次数最多。使用 C++ 时,处理此问题的最简单方法是将每个字符插入到 map
中。我必须在 C# 中做同样的事情吗?有没有一种使用 LINQ 的优雅方法?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
注意:
"aaaabbbb"
的情况,只会返回其中之一(感谢 xanatos 的评论)。如果您需要最大计数的所有元素,请改用 Albin 的解决方案。Notes:
"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.这是因为有人要求2.0版本,所以没有LINQ。
相反,这适用于 LINQ 版本。它将提取配对的“最佳”(aaaabbbb == a,b)。如果 str == String.Empty 则不起作用。
This because someone asked for a 2.0 version, so no LINQ.
Instead this for the LINQ version. It will extract paired "bests" (aaaabbbb == a, b). It WON'T work if str == String.Empty.
受斯蒂芬的回答启发,几乎相同:
更新:对此答案与Jodrell的 回答(发布版本,调试器分离,哦,是的)
Inspired from Stephen's answer, almost the same:
Update: Did a quick benchmarking of this answer vs Jodrell's answer (release build, debugger detached, oh yes)
编辑3
这是我的最后一个答案,我认为它(只是)遮蔽了Nawfal在较长序列上的性能。
然而,鉴于 Nawfal 的答案 的复杂性降低,并且其更通用的性能,特别是与问题相关,我会选择那个。
编辑 2编辑如果您想要一个高效的通用解决方案,则需要考虑多个项目可能具有相同频率,从此扩展开始,
此扩展适用于以下所有场景
,或者
请注意,
mostFrequent
是KeyValuePair>
。如果您愿意,您可以将其简化为另一个扩展,
显然可以使用它,因此,
这里
mostFrequent
是一个IEnumerable
。EDIT 3
Here is my last answer which I think (just) shades Nawfal's for performance on longer sequences.
However, given the reduced complexity of Nawfal's answer, and its more universal performance, especially in relation to the question, I'd choose that.
EDIT 2EDITIf you want an efficient generic solution, that accounts for the fact that multiple items could have the same frequency, start with this extension,
This extension works in all of the following scenarios
or,
Note that
mostFrequent
is aKeyValuePair<int, IEnumerable<char>>
.If so minded you could simplify this to another extension,
which obviously could be used thus,
here,
mostFrequent
is anIEnumerable<char>
.找到最简单且没有内置函数的
示例代码和链接
了解有关如何获得最大出现次数以及流程的更多信息。
如何获取字符串中出现的最大字符数和最大出现次数
Find the simplest and without built in function used
sample code and links
Know more about how to get max occurrence and what is the flow.
How to get max occurred character and max occurrence in string
有许多不同的方法可以解决这个问题。
您可以根据自己的喜好进行选择。列举其中之一。
我从下面的链接中了解到了所有这些内容,供您参考。
There are many different ways to solve the problem.
You can choose based on your preferences. Listing one of it.
I learned all of them from the below link for your reference.
代码:
Code:
这是 Femaref 的解决方案,经过修改后,如果多个字母的计数匹配,则返回多个字母。它不再是一句台词,但仍然相当简洁,并且应该具有相当的性能。
This is Femaref's solution modified to return multiple letters if their Count matches. Its no longer a one-liner but still reasonably concise and should be fairly performant.
使用 LINQ 和字典数据结构作为查找列表的不同方法:
A different approach using LINQ and a Dictionary data structure as a lookup list: