fast JavaScript code using replace()


  • 0
    E
    var wordPattern = function(pattern, str) {
        var newStr = str.split(" ");
        var replaced = {}, used = {};
        var tmpPattern = pattern.split("").join(" ") + " ";
        for(let i = 0; i < pattern.length; i++){
            var letter = pattern[i] + " ";
            if(replaced[letter] !== undefined) continue;
            if(used[newStr[i]] !== undefined) return false;
            var reg = new RegExp(letter, 'g');
            tmpPattern = tmpPattern.replace(reg, newStr[i]);
            replaced[letter] = 1;
            used[newStr[i]] = 1;
        }
        str = str.replace(/\s+/g, "");
        return tmpPattern === str;
    };
    

Log in to reply
 

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