Solution with hashmap but failed in the last test case


  • 0
    public class Solution {
        public boolean isAnagram(String s, String t) {
    
            if(s.length()!=t.length()) return false;    
        	char ch;
        	Map<Character, Integer> smap=new HashMap<Character, Integer>();
        	Map<Character, Integer> tmap=new HashMap<Character, Integer>();
        	for(int i=0;i<s.length();i++){
        		ch=s.charAt(i);
        		smap.put(ch, (int)smap.getOrDefault(ch, 0)+1);
        		ch=t.charAt(i);
        		tmap.put(ch, (int)tmap.getOrDefault(ch, 0)+1);
        	}
        	
        	for(Map.Entry entry:smap.entrySet()){
        		ch=(char)entry.getKey();
        		if(!tmap.containsKey(ch)) return false;
        		if(tmap.get(ch)!=entry.getValue()) return false;
        	}
        	return true;
        }
    }

  • 0
    V
    This post is deleted!

  • 0
    V

    @NaLanZiYi The reason is that Java compares Integer as "object", not "int" when the value is beyond -128 and 127. You should do a type cast to compare the value.


  • 0
    R

    @vanyee Thanks dude!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.