My Java Solution, HashMap


  • -1
    L
    public boolean wordPattern(String pattern, String str) {
        String[] array = str.split(" ");
        int length = pattern.length();
        char[] pat = pattern.toCharArray();
        
        if(pat.length != array.length){
            return false;
        }
        
        HashMap hms = new HashMap();
        HashMap hmt = new HashMap();
        
        for(int i = 0; i < pat.length; i++){
            if(hms.put(pat[i], pat[i]) != hmt.put(array[i],pat[i])){
                return false;
            }
        }
        
        return true;
    }

  • 0
    M

    if(hms.put(pat[i], pat[i]) != hmt.put(array[i],pat[i]))

    What does this boolean statement mean?


  • 0
    L

    You have 2 arrays, one of chars, and another one of strings. Taking you can't have repeated keys in a hashmap, if you can't put the same value for a given key position thats because they are different.


Log in to reply
 

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