首页 > 解决方案 > HashMap.containsKey(s.charAt(i)) 计算结果为 true 但 map.get(s.charAt(i)) 导致空指针异常?

问题描述

给定两个字符串 s 和 t,我试图找到使 s 成为 t 字谜的最小步数。出于某种原因,在尝试从映射中获取键时,我得到了一个空指针异常,即使我在 if 语句中验证了映射确实包含该键。为什么会这样?

class Solution {
    public int minSteps(String s, String t) {
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < t.length(); i++) {
            if (map.containsKey(t.charAt(i))) {
                map.put(t.charAt(i), map.get(t.charAt(i) + 1));
            } else {
                map.put(t.charAt(i), 1);
            }
        }
        int steps = 0;
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                int q = map.get(s.charAt(i)); //results in null pointer exception
                if (q < 1) {
                    steps++;
                } else {
                    map.put(s.charAt(i), q-1);
                }
            } else {
                steps++;
            }
        }
        return steps;
    }
}

标签: javanullpointerexceptionhashmap

解决方案


推荐阅读