java, how to find the most repeated character

www‮uttual.‬ri.com
java, how to find the most repeated character

To find the most repeated character in a string in Java, you can use the following approach:

  1. Create a HashMap to store the frequency of each character in the string.
  2. Iterate through the string, and for each character, increment the count in the HashMap.
  3. After iterating through the entire string, iterate through the HashMap to find the character with the highest frequency.
  4. If multiple characters have the same highest frequency, you can return any of them.

Here is an example of how this approach could be implemented:

import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    String str = "Hello World!";
    HashMap<Character, Integer> charCount = new HashMap<>();

    // Count the frequency of each character
    for (int i = 0; i < str.length(); i++) {
      char c = str.charAt(i);
      if (charCount.containsKey(c)) {
        charCount.put(c, charCount.get(c) + 1);
      } else {
        charCount.put(c, 1);
      }
    }

    // Find the character with the highest frequency
    char mostRepeated = ' ';
    int maxCount = 0;
    for (char c : charCount.keySet()) {
      if (charCount.get(c) > maxCount) {
        mostRepeated = c;
        maxCount = charCount.get(c);
      }
    }

    System.out.println("Most repeated character: " + mostRepeated);
  }
}

This code will output "Most repeated character: l" because the letter "l" is the most repeated character in the string "Hello World!".

Keep in mind that this approach has a time complexity of O(n), where n is the length of the string, as it involves iterating through the string twice. If you need to optimize for performance, you may want to consider using a different algorithm.

Created Time:2017-11-03 23:27:14  Author:lautturi