Print maximum occurring character in a String

In this post, we will see how to print the maximum occurring character in a String.


Problem

Print maximum occurring character in a String
For example:

String 1: java2blog tutorial
Character: a has occurred maximum times in String: 3
———————-
String 2: This is test message
Character: s has occurred maximum times in String: 5

Solution

Simple solution can be we can sort the String and then find maximum occurring character by comparing consecutive characters.

Can we do better?
Yes, we can use hashmap and keep track of maximum count with the help of hashmap.
Here is simple algorithm.

  • Initialize a HashMap with Key as character and value as count.
  • Iterate over input string.
  • If character is already present in HashMap, then increment the count else put the value as 1.
  • Keep the track of maximum count in the process.
  • Once we are done with iterate, iterate over HashMap and find character with the help of maximum count.

Program to print maximum occurring character in a String

When you run above program, you will get below output:

String 1: java2blog tutorial
Character: a has occurred maximum times in String: 3
———————-
String 2: This is test message
Character: s has occurred maximum times in String: 5

Please note that if there are more than two character which can have same maximum count, it will print one of them.

That’s all about how to Print maximum occurring character in a String.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *