Interview question: count the characters that appear most frequently in the string

Count the characters that appear most frequently in the string, assuming no repeated characters

analysis

Grasp the characteristics of HashMap:
If a duplicate key is encountered, the previous duplicate key will be returned.
If a non-duplicated key is encountered, null will be returned

So the idea is very clear!
Prepare two Maps, one is used to store the string, the key is each character of the string, the value is 1 and the
other is used to store the number of repetitions when repeated characters appear, the key is the repeated character, and the value is the number of repetitions.

But how do you get the largest value and the corresponding key at this time? It's a headache! !
You can find the largest value first. Then get the entrySet of the map, take out the value comparison from it, if you find the largest value, take out its key again! !

Code

public static Character maxChar(String strs){
    
    
    char[] chars = strs.toCharArray();
    Map<Character,Integer> maps = new HashMap<>();

    Map<Character,Integer> duplicate = new HashMap<>();
    for (int i = 0; i < chars.length; i++) {
    
    
        duplicate.put(chars[i], 1);
    }

    for (int i = 0; i < chars.length; i++) {
    
    
        Integer put = maps.put(chars[i], 1);
        //说明chars[i]字符已经重复了,如何处理呢
        if(put != null){
    
    
            duplicate.put(chars[i],duplicate.get(chars[i])+1);
        }
    }

    int maxValue = 0;

    Set<Character> characters = duplicate.keySet();
    for (Character character : characters) {
    
    
        if(duplicate.get(character) > maxValue){
    
    
            maxValue = duplicate.get(character);
        }
    }

    Set<Map.Entry<Character, Integer>> entries = duplicate.entrySet();
    for (Map.Entry<Character, Integer> entry : entries) {
    
    
        if(entry.getValue().equals(maxValue)){
    
    
            return entry.getKey();
        }
    }
    return null;
}

Guess you like

Origin blog.csdn.net/JAYU_37/article/details/107267409