Skip to content

Commit 96fb566

Browse files
Merge pull request #70 from aadityasinha-dotcom/maxFrequentCharacters
maximum freq character
2 parents 3b28ad9 + 3e5054c commit 96fb566

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

0 commit comments

Comments
 (0)