0

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;
    }
}
Alisha
  • 41
  • 5
  • 1
    `map.containsKey(t.charAt(i))` is searching for a `Character`-typed key, whereas `map.get(t.charAt(i) + 1)` is calling `get` with an `Integer` object. You need to look at the types of keys you search with. An `Integer` won't ever equal a `Character`. – ernest_k Nov 06 '20 at 07:57
  • 2
    I think `map.get(t.charAt(i) + 1)` is supposed to be `map.get(t.charAt(i)) + 1` – jr593 Nov 06 '20 at 08:01

0 Answers0