You can use a Map to store the count of each character in the string. Then, you can traverse the map to find the maximum count of any character. Here's the Java code to achieve this:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String str = "aabbcccaaa";
Map<Character, Integer> charCount = new HashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
int maxCount = 0;
for (int count : charCount.values()) {
maxCount = Math.max(maxCount, count);
}
System.out.println("Maximum count of any character: " + maxCount);
}
}
In the code above, we first initialize an empty HashMap called charCount. Then, we iterate over the characters in the string and increment the count for each character in the map using the getOrDefault() method.
After that, we initialize a variable maxCount to store the maximum count of any character. We traverse the map to find the maximum count by comparing the current count with maxCount using the Math.max() method.
Finally, we print the maximum count of any character. This solution has a time complexity of O(n), where n is the length of the string, as we only iterate over the string once. The space complexity is O(m), where m is the number of distinct characters in the string. In the worst case, m can be equal to 26 (the number of letters in the English alphabet).
Keep in mind that this solution doesn't take into account the repetition of consecutive identical letters. If you need to find the maximum count of any letter while taking into account consecutive identical letters, you can use the following solution:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String str = "aabbcccaaa";
Map<Character, Integer