java - 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;
}
}
解决方案
推荐阅读
- javascript - 如何将事件绑定到 epub.js 中的演绎版
- twitter-bootstrap - 带有文本区域的引导弹出窗口:无法水平调整大小
- c# - Unity Android 触控输入重置
- hyperledger-composer - 在事务期间修改资源(参与者)的数组属性
- azure - 通过 azure 数据工厂将数据从 oracle 复制到 azure blob 存储
- c# - 泛型类型和接口
- php - 不带括号的命名空间的结束语法(与带括号的命名空间混合)
- java - HBase prefixFilter 与 startRow 和 PageFilter 一起使用
- javascript - componentDidMount() 中调用函数的问题
- spring - 使用 APPLICATION_OCTET_STREAM 的 Spring Boot 406 错误