Why does this HashMap attempt fail for 1 test case?


  • 0
    2

    probably not the cleanest/fastest way, but after adding everything to the 2 maps(using one for loop since the two lists' size should be the same), then i'll check the two Map's values for the given key to see if the counts match.

    seems like the "really long string" testcase was failed but i can't see why?

    thanks

    public class Solution {
        public boolean isAnagram(String s, String t) {
            if(s.length() != t.length()){
                return false;
            }
                    
            Map<Character, Integer> map_s = new HashMap<Character, Integer>();
            Map<Character, Integer> map_t= new HashMap<Character, Integer>();
            
            char[] char_s = s.toCharArray();
            char[] char_t = t.toCharArray();
            
            for(int i=0;i<char_s.length;i++){
                if(!map_s.containsKey(char_s[i])){
                    map_s.put(char_s[i], 1);
                }else{
                    map_s.put(char_s[i], map_s.get(char_s[i])+1);
                }
                
                if(!map_t.containsKey(char_t[i])){
                    map_t.put(char_t[i], 1);
                }else{
                    map_t.put(char_t[i], map_t.get(char_t[i])+1);
                }
            }
            
            for(Character c : map_s.keySet()){
                if(map_t.get(c) != map_s.get(c)){
                    return false;
                }
            }
            return true;
        }
    }
    

Log in to reply
 

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