写代码遇到一个bug
原代码:
public static String minWindow(String s, String t) {
HashMap<Character, Integer> need = new HashMap<>();
HashMap<Character, Integer> window = new HashMap<>();
for (int i = 0; i < t.length(); i++) {
need.put(t.charAt(i), need.getOrDefault(t.charAt(i), 0) + 1);
}
int left = 0;
int rigth = 0;
int valid = 0;
int start = 0;
int minL = Integer.MAX_VALUE;
while (rigth < s.length()) {
char c = s.charAt(rigth);
rigth++;
if (need.containsKey(c)) {
window.put(c, window.getOrDefault(c,0) + 1);
if (window.get(c) == need.get(c)) {
valid++;
}
}
while (valid == need.size()) {
if (rigth - left < minL) {
start = left;
minL = rigth - left;
}
char d = s.charAt(left);
left++;
if (window.containsKey(d)) {
window.replace(d, window.get(d) - 1);
if (window.get(d) < need.get(d)) {
valid--;
}
}
}
}
return (minL == Integer.MAX_VALUE) ? "" : s.substring(start, start+ minL);
}
但是当函数输入的字符串s很大时,会出现未知错误,一开始我也不清楚,后来定位到问题在这一句话:
if (window.get(c) == need.get(c)) {
valid++;
}
改成equal方法就解决了问题:
if (window.get(c).equals(need.get(c))) {
valid++;
}
这是为啥呢?
基本数据类型==比较的是值
引用数据类型==比较的是内存地址
由于HashMap定义的是HashMap<Character, Integer>,取的value进行比较的时候应该用equal()方法才对!