Strings-Max Frequency Character [codingblocks]
Take as input S, a string. Write a function that returns the character with maximum frequency. Print the value returned.
Input Format
String
Constraints
A string of length between 1 to 1000.
Output Format
Character
Sample Input
aaabacb
Sample Output
a
Explanation
For the given input string, a appear 4 times. Hence, it is the most frequent character.
JAVA Code:
IDE Code: https://ide.geeksforgeeks.org/VUq5fnc859
/* Amit Kumar 14-12-2020 IDE Code: https://ide.geeksforgeeks.org/VUq5fnc859 */ package String; import java.util.HashMap; import java.util.Scanner; public class Strings_MaxFrequencyCharacter { public static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { String str = scanner.next(); int max = Integer.MIN_VALUE; char maxCountChar = '\0'; HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();hashMap.get(0); for (int i=0; i<str.length(); i++) { if (hashMap.containsKey(str.charAt(i))) { hashMap.put(str.charAt(i), hashMap.get(str.charAt(i)) + 1); } else { hashMap.put(str.charAt(i), 1); } if (hashMap.get(str.charAt(i)) > max) { max = hashMap.get(str.charAt(i)); maxCountChar = str.charAt(i); } } System.out.println(maxCountChar); } }
Comments
Post a Comment