Skip to content

290. Word Pattern

https://leetcode.com/problems/word-pattern/

js
/**
 * @param {string} pattern
 * @param {string} str
 * @return {boolean}
 */
var wordPattern = function(pattern, str) {
    var keys = pattern.split('');
    var vals = str.split(' ');

    if (keys.length !== vals.length) {
        return false;
    }

    var kv = {};
    var vk = {};

    for (var i = 0; i < keys.length; i++) {
        var k = keys[i];
        var v = vals[i];

        if (!kv[k] && !vk[v]) {
            kv[k] = v;
            vk[v] = k;
        } else if (!kv[k] || !vk[v]) {
            return false;
        }
    }

    return true;
};
py
class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        str = str.split()
        if len(pattern) != len(str):
            return False

        kv, vk = {}, {}
        for k, v in zip(pattern, str):
            if k not in kv and v not in vk:
                kv[k], vk[v] = v, k
            elif k not in kv or v not in vk:
                return False

        return True