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;
}