Java solution, with comments.


  • 1
    Z
     // use Object as key and val, not char or str
    public boolean wordPattern(String pattern, String str) {
        String[] strs = str.split(" ");
        if(pattern.length() != strs.length)
            return false;
    
        Map<Object, Object> map = new HashMap<>();
        for(int i =0; i < strs.length; i ++){
            char p = pattern.charAt(i);
            String s = strs[i];
    
            if(map.containsKey(p)!= map.containsKey(s))
                return false;
            if(map.containsKey(p)){
                if(!map.get(p).equals(map.get(s)))
                    return false;
            }
            else{// map does not have p or s.
                // p => i => s, forms  bijection.
                map.put(p, i);
                map.put(s, i);    
            }
    
        }
    
        return true;
    }

  • 0
    I

    @ZZJJ Though the map contains twice the number of elements, your approach was unique. Great solution!


Log in to reply
 

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