class Solution {
public long validSubstringCount(String word1, String word2) {
HashMap<Character, Integer> map = new HashMap<>();
for (int i=0; i<word2.length(); i++) {
char val = word2.charAt(i);
if (!map.containsKey(val)) map.put(val,1);
else map.put(val, map.get(val)+1);
}
HashMap<Character, Integer> run = new HashMap<>();
int runcount = 0;
int start = 0;
int end = 0;
int ret = 0;
int count = 0;
while (start<word1.length() && end<word1.length()) {
while (end<word1.length() && runcount<map.size()) {
count++;
char val = word1.charAt(end);
if (map.containsKey(val)) {
if (!run.containsKey(val)) run.put(val, 1);
else run.put(val, run.get(val)+1);
if (run.get(val)==map.get(val)) runcount++;
if (val=='f') System.out.println(run.get(val) + " " + map.get(val) + " " + (run.get(val)==map.get(val)));
}
end++;
}
while (start<end && runcount==map.size()) {
char x = word1.charAt(start);
ret+=(word1.length()-end+1);
if (map.containsKey(x)) {
run.put(x, run.get(x)-1);
if (run.get(x)<map.get(x)) runcount--;
}
start++;
}
}
return ret;
}
}
The main problem I have is that the boolean part is not evaluating properly. In particular, run.get(val)==map.get(val) when val=='f' is evaluating to "false" even when the values are clearly equivalent, e.g. when run.get(val) and map.get(val) are both 132.
This works for small integer values, and I am comparing as part of a HashMap, so not the same as another similar-topic question.
Use equals()
, not ==
when comparing two objects. You are comparing Integer
elements, not int
, meaning that the ==
will do the comparison between the heap address values of the two objects. equals
will compare the actual values.
Take a look over here: How can I properly compare two Integers in Java?. This is the same for all primitive wrappers. This is the same for all object types. Wrappers aren't treated in a special manner.