查找字符串中出现次数最多的字符? [英] Find character with most occurrences in string?

查看:417
本文介绍了查找字符串中出现次数最多的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个字符串:

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

注意:

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆