Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find character with most occurrences in string?

Tags:

For example, I have a string:

"abbbbccd" 

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?

like image 515
Chan Avatar asked Feb 21 '11 18:02

Chan


People also ask

How do you find the most frequently occurring character in a string?

Algorithm for Maximum Occurring CharacterInitialize the hash table of size 256 with zeros. Iterate over the input string and store the frequency of each element in the hash table. Take the character with the maximum frequency as an answer. Print the answer.

How do you find the maximum occurring character in a string python?

Method 2 : Using collections.Counter() + max() The most suggested method that could be used to find all occurrences is this method, this actually gets all element frequency and could also be used to print single element frequency if required. We find maximum occurring character by using max() on values.


1 Answers

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
like image 55
Femaref Avatar answered Oct 27 '22 00:10

Femaref