File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+
2+ import java .util .*;
3+
4+ public class Max_Freq_Character {
5+
6+ public static void main (String [] args ) {
7+
8+ Scanner sc = new Scanner (System .in );
9+ String str = sc .next ();
10+ System .out .println (maxFreqChar (str ));
11+ sc .close ();
12+
13+ }
14+
15+ private static char maxFreqChar (String str ) {
16+
17+ HashMap <Character , Integer > map = new HashMap <>(); // creating a hashmap which store frequency of each characters
18+
19+ for (int i = 0 ; i < str .length (); i ++) {
20+ char ch = str .charAt (i );
21+ if (map .containsKey (ch )) {
22+ map .put (ch , map .getOrDefault (ch ,0 )+1 ); // incrementing frequency of each character
23+ }else {
24+ map .put (ch , 1 );
25+ }
26+ }
27+
28+ Set <Character > keys = map .keySet (); // making a set of distinct character(non repeating)
29+ char maxChar = ' ' ;
30+ int maxFreq = Integer .MIN_VALUE ;
31+ for (char key : keys ) { // iterating each distinct character from the set
32+ if (map .get (key )>maxFreq ) { // getting frequency of each character and checking if it is the largest or not
33+ maxFreq = map .get (key ); // updating the maximum fequency of the character
34+ maxChar = key ; // updating the maximum occurring character
35+ }
36+ }
37+ return maxChar ;
38+ }
39+
40+ }
You can’t perform that action at this time.
0 commit comments