Javascript solution 108ms


  • 0
    N
    var wordPattern = function(pattern, str) {
    var arr = str.split(" "),
        i = 0,
        usedarr = [],
        usedSymbol = function(symbol) {
            var k,
            uLength = usedarr.length;
            for (k = 0; k < uLength; k++) {
                if (symbol === usedarr[k]) {
                    return false;
                }
            } 
            return true;
        },
        replaceArr = function(oldElem, newElem) {
            var k;
            for (k = 0; k < arr.length; k++) {
                if (arr[k] === oldElem) {
                    arr[k] = newElem;
                }
            }
        }
    if (pattern !== "")  {  
    while (i < arr.length) {
        if (usedSymbol(pattern[i])) {
            replaceArr(arr[i], pattern[i]);
            usedarr.push(pattern[i]);
        }        
        i++;
    }
    }
    return arr.join().replace(new RegExp(",",'g'),"") === pattern;
    

    };


Log in to reply
 

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