Javascript Solution


  • 0
    var wordPattern = function(pattern, str) {
    
        var t = str.split(" ");
    
        if (pattern.length !== t.length) {
            return false;
        }
    
        var hash = {};
        var mappedWords = {};
    
        for (var i = 0; i < pattern.length; i++) {
            if (!hash[pattern[i]] && !mappedWords[t[i]]) {
                // Hash entry doesn't exist and the word hasn't been mapped yet
                hash[pattern[i]] = t[i];
                mappedWords[t[i]] = true;
            } else {
                // Hash entry exists. Now, check if that hash(pattern[i]) === t[i]
                if (hash[pattern[i]] !== t[i]) {
                    return false;
                }
            }
        }
    
        return true;
    }
    

Log in to reply
 

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