Java solution, with comments.

  • 1
     // 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;
                    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

    @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.