1
public static boolean isIsomorphic(String s, String t) {
    HashMap<Character, Character> res1 = new HashMap<Character, Character>();
    HashMap<Character, Character> res2 = new HashMap<Character, Character>();
    char[] sToArray = s.toCharArray();
    char[] tToArray = t.toCharArray();
    if (s == null && t == null)
        return true;
    if (s == null || t == null || s.length() != t.length())
        return false;
    for (int i = 0; i < sToArray.length; i++) {
        ***if ((!res1.containsKey(sToArray[i])) && (!res2.containsKey(tToArray[i])))*** {
            res1.put(sToArray[i], tToArray[i]);
            res2.put(tToArray[i], sToArray[i]);

        } else {

            if ((res1.get(sToArray[i]) != tToArray[i]) || (res2.get(tToArray[i]) != sToArray[i]))
                return false;

        }

    }
    return true;

}

Given two strings s and t, determine if they are isomorphic. When the test case is "ab" "aa"; there will be an nullpointerexception for if ((!res1.containsKey(sToArray[i])) && (!res2.containsKey(tToArray[i]))) I checked res1 does not equal to null and res2 does not equal to null. Could anybody tell the reason? Thanks very much!

tjuli
  • 19
  • 3

1 Answers1

1

What's probably happening is that res1.get(sToArray[i]) is null. You then compare that Character with a char, which requires an unboxing operation on the Character - but it's null and a NPE is thrown.

Note that res1.containsKey(sToArray[i]) will return true if there is a null value associated with that key.

assylias
  • 321,522
  • 82
  • 660
  • 783