Given a string, Write an efficient java method to return maximum occurring character in the input string
E.g., if input string is “test” then function should return ‘ t ‘ (the most occurring character in the string).
Input:
Enter any String: test
Output:
Most Repeated character: t and its Count is: 2
import java.io.*; import java.util.Scanner; public class temp{ static void maxim(String str){ int[] arr = new int[str.length()]; for (int i=0;i<str.length();i++){ arr[i]=0; for (int j = 0;j<str.length();j++){ if(str.charAt(i)==str.charAt(j)){ arr[i]++; } } } int max = arr[0]; int max2=0; for(int i = 0; i<arr.length;i++){ if (arr[i]>max){ max=arr[i]; max2 = i; } } System.out.println(String.format("Most Repeated character: %s and its Count is: %d",str.charAt(max2),max)); } public static void main(String[] args){ Scanner scan = new Scanner(System.in); System.out.print("Enter any string: "); String str = scan.nextLine(); maxim(str); } }
INPUT_1:
Enter any string: test
OUTPUT:
Most Repeated character: t and its Count is: 2
INPUT_2:
Enter any string: jojo’s bizzare adventure
OUTPUT:
Most Repeated character: e and its Count is: 3
INPUT_3:
Enter any string: danmachi
OUTPUT:
Most Repeated character: a and its Count is: 2
INPUT_4:
Enter any string: kakegurui
OUTPUT:
Most Repeated character: k and its Count is: 2
INPUT_5:
Enter any string: bigbangtheory
OUTPUT:
Most Repeated character: b and its Count is: 2
INPUT_6:
Enter any string: karakuri circus
OUTPUT:
Most Repeated character: r and its Count is: 3
INPUT_7:
Enter any string: How not to summon demon lord
OUTPUT:
Most Repeated character: o and its Count is: 6
ILLUSTRATION