Print maximum occurring character in a String

ghz 10months ago ⋅ 107 views

To print the maximum occurring character in a string, you can use a hashmap to count the occurrences of each character and then find the character with the maximum count. Here's a Java implementation:

import java.util.HashMap;
import java.util.Map;

public class MaxOccurringCharacter {

    public static char maxOccurringCharacter(String str) {
        if (str == null || str.isEmpty()) {
            throw new IllegalArgumentException("Input string is null or empty");
        }

        Map<Character, Integer> frequencyMap = new HashMap<>();

        // Count the occurrences of each character
        for (char ch : str.toCharArray()) {
            frequencyMap.put(ch, frequencyMap.getOrDefault(ch, 0) + 1);
        }

        // Find the character with maximum occurrence
        char maxChar = str.charAt(0);
        int maxCount = frequencyMap.get(maxChar);

        for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxChar = entry.getKey();
                maxCount = entry.getValue();
            }
        }

        return maxChar;
    }

    public static void main(String[] args) {
        String str = "abbcccdddd";
        char maxChar = maxOccurringCharacter(str);
        System.out.println("Maximum occurring character: " + maxChar); // Output: 'd'
    }
}

In this implementation:

  • We use a HashMap to store the frequency of each character in the input string.
  • We iterate through the string and update the frequency map.
  • After counting all occurrences, we iterate through the map to find the character with the maximum occurrence.
  • We return the character with the maximum occurrence.
  • We test the implementation with an example string and print the maximum occurring character.