w3resource

Java String Exercises: Find the maximum occurring character in a string

Java String: Exercise-43 with Solution

Write a Java program to find the maximum occurring character in a string.

Pictorial Presentation:

Java String Exercises: Find the maximum occurring character in a string

Sample Solution:

Java Code:

import java.util.*;
public class Main {
 static final int N = 256;
 static char MaxOccuringChar(String str1) {
  int ctr[] = new int[N];
  int l = str1.length();
  for (int i = 0; i < l; i++)
   ctr[str1.charAt(i)]++;
  int max = -1;
  char result = ' ';

  for (int i = 0; i < l; i++) {
   if (max < ctr[str1.charAt(i)]) {
    max = ctr[str1.charAt(i)];
    result = str1.charAt(i);
   }
  }

  return result;
 }
 public static void main(String[] args) {
  String str1 = "test string";
  System.out.println("The given string is: " + str1);
  System.out.println("Max occurring character in the given string is: " + MaxOccuringChar(str1));
 }
}

Sample Output:

The given string is: test string
Max occurring character in the given string is: t

Flowchart:

Flowchart: Java String Exercises - Find the maximum occurring character in a string

Visualize Java code execution (Python Tutor):


Find the character with the most appearances.

Main.java Code:

//MIT License: https://bit.ly/35gZLa3
import java.util.concurrent.TimeUnit;

public class Main {

    private static final String TEXT = "My high school, the Illinois Mathematics and Science Academy, "
            + "showed me that anything is possible and that you're never too young to think big. "
            + "At 15, I worked as a computer programmer at the Fermi National Accelerator Laboratory, "
            + "or Fermilab. After graduating, I attended Stanford for a degree in economics and "
            + "computer science.";

    public static void main(String[] args) {

        System.out.println("Input text: \n" + TEXT + "\n");

        System.out.println("HashMap based solution:");
        long startTimeV1 = System.nanoTime();

        Pair pairV1 = Strings.maxOccurenceCharacterV1(TEXT);

        displayExecutionTime(System.nanoTime() - startTimeV1);
        System.out.println("Character: " + pairV1.character);
        System.out.println("Occurrences :" + pairV1.occurrences);

        System.out.println();
        System.out.println("ASCII codes based solution:");
        long startTimeV2 = System.nanoTime();

        Pair pairV2 = Strings.maxOccurenceCharacterV2(TEXT);

        displayExecutionTime(System.nanoTime() - startTimeV2);
        System.out.println("Character: " + pairV2.character);
        System.out.println("Occurrences :" + pairV2.occurrences);

        System.out.println();
        System.out.println("Java 8, functional-style solution:");
        long startTimeV3 = System.nanoTime();

        Pair pairV3 = Strings.maxOccurenceCharacterV3(TEXT);

        displayExecutionTime(System.nanoTime() - startTimeV3);
        System.out.println("Character: " + pairV3.character);
        System.out.println("Occurrences :" + pairV3.occurrences);
    }

    private static void displayExecutionTime(long time) {
        System.out.println("Execution time: " + time + " ns" + " ("
                + TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS) + " ms)");
    }
}

Pair.java Code:

//MIT License: https://bit.ly/35gZLa3
public final class Pair<V, C> {

    final V character;
    final C occurrences;

    public Pair(V character, C occurrences) {
        this.character = character;
        this.occurrences = occurrences;
    }

    static <V, C> Pair<V, C> of(V character, C occurrences) {
        return new Pair<>(character, occurrences);
    }

    @Override
    public int hashCode() {
        return character.hashCode() ^ character.hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) {
            return false;
        }

        Pair obj = (Pair) o;
        return this.character.equals(obj.character)
                && this.occurrences.equals(obj.occurrences);
    }
}

Strings.java Code:

//MIT License: https://bit.ly/35gZLa3
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;

public final class Strings {

    private static final int EXTENDED_ASCII_CODES = 256;

    private Strings() {
        throw new AssertionError("Cannot be instantiated");
    }

    public static Pair<Character, Integer> maxOccurenceCharacterV1(String str) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return Pair.of(Character.MIN_VALUE, -1);
        }

        Map<Character, Integer> counter = new HashMap<>();
        char[] chStr = str.toCharArray();
        for (int i = 0; i < chStr.length; i++) {

            char currentCh = chStr[i];
            if (!Character.isWhitespace(currentCh)) { // ignore spaces
                Integer noCh = counter.get(currentCh);
                if (noCh == null) {
                    counter.put(currentCh, 1);
                } else {
                    counter.put(currentCh, ++noCh);
                }
            }
        }

        int maxOccurrences = Collections.max(counter.values());

        char maxCharacter = Character.MIN_VALUE;
        for (Entry<Character, Integer> entry : counter.entrySet()) {
            if (entry.getValue() == maxOccurrences) {
                maxCharacter = entry.getKey();
            }
        }

        return Pair.of(maxCharacter, maxOccurrences);
    }

    public static Pair<Character, Integer> maxOccurenceCharacterV2(String str) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return Pair.of(Character.MIN_VALUE, -1);
        }

        int maxOccurrences = -1;
        char maxCharacter = Character.MIN_VALUE;

        char[] chStr = str.toCharArray();
        int[] asciiCodes = new int[EXTENDED_ASCII_CODES];

        for (int i = 0; i < chStr.length; i++) {
            char currentCh = chStr[i];
            if (!Character.isWhitespace(currentCh)) { // ignoring space

                int code = (int) currentCh;
                asciiCodes[code]++;
                if (asciiCodes[code] > maxOccurrences) {
                    maxOccurrences = asciiCodes[code];
                    maxCharacter = currentCh;
                }
            }

        }

        return Pair.of(maxCharacter, maxOccurrences);
    }

    public static Pair<Character, Long> maxOccurenceCharacterV3(String str) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return Pair.of(Character.MIN_VALUE, -1L);
        }

        return str.chars()
                .filter(c -> Character.isWhitespace(c) == false) // ignoring space
                .mapToObj(c -> (char) c)
                .collect(groupingBy(c -> c, counting()))
                .entrySet()
                .stream()
                .max(comparingByValue())
                .map(p -> Pair.of(p.getKey(), p.getValue()))
                .orElse(Pair.of(Character.MIN_VALUE, -1L));
    }
}

Sample Output:

Input text: 
My high school, the Illinois Mathematics and Science Academy, showed me that anything is possible and that you're never too young to think big. At 15, I worked as a computer programmer at the Fermi National Accelerator Laboratory, or Fermilab. After graduating, I attended Stanford for a degree in economics and computer science.

HashMap based solution:
Execution time: 3438752 ns (3 ms)
Character: e
Occurrences :29

ASCII codes based solution:
Execution time: 215566 ns (0 ms)
Character: e
Occurrences :29

Java 8, functional-style solution:
Execution time: 120723045 ns (120 ms)
Character: e
Occurrences :29

Flowchart:

Flowchart: Java String Exercises - Find the character with the most appearances
Flowchart: Java String Exercises - Find the character with the most appearances
Flowchart: Java String Exercises - Find the character with the most appearances

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to print list items containing all characters of a given word.
Next: Write a Java program to reverse a string using recursion

What is the difficulty level of this exercise?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH