Find character with most occurrences in string?

前端 未结 10 1051
一生所求
一生所求 2020-11-27 17:49

For example, I have a string:

\"abbbbccd\"

b has the most occurrences. When using C++, the easiest way to handle this is inser

10条回答
  •  日久生厌
    2020-11-27 18:48

    input.GroupBy(x => x).OrderByDescending(x => x.Count()).First().Key
    

    Notes:

    • 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

提交回复
热议问题