0

I used a foolish method to solve this problem. The program seems right but I failed the last test case.

I replaced "sc.get(c)!= tc.get(c)" with "!sc.get(c).equals(tc.get(c))" and then I passed. What's wrong with my code and I want to know more details! TX!! :)

Here are my codes:

 public boolean isAnagram(String s, String t) {
    if(s.length()!=t.length()){
        return false;
    }
    HashMap<Character,Integer> sc = new HashMap<>();
    HashMap<Character,Integer> tc = new HashMap<>();

    for(char c : s.toCharArray()){
        if(sc.keySet().contains(c)){
            sc.put(c,sc.get(c)+1);
        }else{
            sc.put(c,1);
        }
    }

    for(char c : t.toCharArray()){
        if(tc.keySet().contains(c)){
            tc.put(c,tc.get(c)+1);
        }else{
            tc.put(c,1);
        }
    }

    for(char c : sc.keySet()){
        if(!tc.keySet().contains(c) || sc.get(c)!= tc.get(c)){
            return false;
        }
    }
    for(char c : tc.keySet()){
        if(!sc.keySet().contains(c)){
            return false;
        }
    }
    return true;
}

enter image description here

  • 2
    Does this answer your question? [What is the difference between == and equals() in Java?](https://stackoverflow.com/questions/7520432/what-is-the-difference-between-and-equals-in-java) – Prasanth Rajendran Aug 20 '21 at 17:11

1 Answers1

0

sc.get(c) and tc.get(c) returns an Integer, not an int. Since Integer is a wrapper class and not a primitive type, we have to use .equals() for content comparison.
sc.get(c) == tc.get(c) checks if the memory address of the object returned by sc.get(c) is equal to that of tc.get(c).

David
  • 98
  • 5