要修改这段代码,需要解决几个问题:

  1. Map<String[], String> charCount = new HashMap<>(); 这行代码的语法是错误的,应该将其修改为 Map<Character, Integer> charCount = new HashMap<>();,将String[]改为Character

  2. charCount.put(c, charCount.getOrDefault(c, 0) + 1); 这行代码的逻辑也是错误的,应该将其修改为 charCount.put(c, charCount.getOrDefault(c, 0) + 1);,将charCount.getOrDefault(c, 0)改为charCount.getOrDefault(c, 0) + 1

  3. HashMap<Character, Integer> wordsCount = new HashMap<>(); 这行代码可以简化为 Map<Character, Integer> wordsCount = new HashMap<>();,不需要使用具体的实现类HashMap

修改后的代码如下:

public static int countGoodStrings(String[] words, String chars) {
    Map<Character, Integer> charCount = new HashMap<>();
    for (char c : chars.toCharArray()) {
        charCount.put(c, charCount.getOrDefault(c, 0) + 1);
    }

    int totalCount = 0;

    for (String word : words) {
        Map<Character, Integer> wordsCount = new HashMap<>();
        boolean isGoodString = true;

        for (char c : word.toCharArray()) {
            wordsCount.put(c, wordsCount.getOrDefault(c, 0) + 1);
            if (!charCount.containsKey(c) || charCount.get(c) < wordsCount.get(c)) {
                isGoodString = false;
                break;
            }
        }
        if(isGoodString){
            totalCount += word.length();
        }
    }
    return totalCount;
}
``
public static int countGoodStringsString words String chars MapString String charCount = new HashMap; for char c charstoCharArray charCountputc charCountgetOrDefaultc 0 + 1

原文地址: https://www.cveoy.top/t/topic/ipFW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录