My 3ms java solution using only one hashmap


  • 8
    B
    public boolean wordPattern(String pattern, String str) {
        if (pattern == null || str == null) {
            return false;
        }
        char[] patterns = pattern.toCharArray();
        String[] strs = str.split(" ");
        if (patterns.length != strs.length) {
            return false;
        }
        Map<Character, String> map = new HashMap<Character, String>();
        for (int i=0; i<patterns.length; i++) {
            if (map.containsKey(patterns[i])) {
                if (!map.get(patterns[i]).equals(strs[i])) {
                    return false;
                }
            } else if (map.containsValue(strs[i])) {
                return false;
            }
            map.put(patterns[i], strs[i]);
        }
        return true;
    }

  • 13
    C

    doesn't map.containsValue() require scans of the table? if so, it would be better to use another hash set containing values.


  • 0
    B

    yeah should have concerned about that. Thanks


Log in to reply
 

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