Java Program to find maximum and minimum occurring character in a string

Java Program to find maximum and minimum occurring character in a string

Example:

Input:  Java is programming language
Output:Min freq : e, max freq : a

Approach

Java

import java.util.HashMap;

public class LargeAndSmallWord {
    public static void main(String[] args) {
        String str = "Java is programming language";
        HashMap<CharacterIntegerfreq = new HashMap<CharacterInteger>();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (!Character.isSpaceChar(ch)) {
                freq.put(ch, freq.getOrDefault(ch, 0) + 1);
            }
        }

        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        char minCh = '\0';
        char maxCh = '\0';

        for (Character ch : freq.keySet()) {
            if (min > freq.get(ch)) {
                minCh = ch;
                min = freq.get(ch);
            }
            if (max < freq.get(ch)) {
                maxCh = ch;
                max = freq.get(ch);
            }

        }
        System.out.println("Min freq : " + minCh + ", max freq : " + maxCh);

    }
}


No comments:

Post a Comment