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?
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.
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.
input.GroupBy(x => x).OrderByDescending(x => x.Count()).First().Key
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With