given two strings s and t, I am trying to find the minimum number of steps to make s an anagram of t. For some reason, I get a null pointer exception when trying to get a key from a map, even after I have verified in the if statement that the map does indeed contain the key. Why is this happening?
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;
}
}