My easy understand JavaScript Solution


  • 0
    S
    var wordPattern = function(pattern, str) {
        //transfer both the pattern and str to array in numbers like 'abcb' to [1,2,3,2]
        var patternInNumberArray = transferToNumber(pattern, true);
        var strInNumberArray = transferToNumber(str, false);
        //if two arrays are the same, then they are in the same pattern
        return patternInNumberArray.toString() == strInNumberArray.toString() ? true : false;
    
        function transferToNumber(string, flag) {
            var res = [],
                hash = {},
                num = 1;
            var a = flag ? string.split('') : string.split(' ');
    
            for (var i = 0; i < a.length; i++) {
                if (!hash[a[i]]) {
                    hash[a[i]] = num;
                    num++;
                }
                res.push(hash[a[i]]);
            }
            return res;
        }
    };
    

Log in to reply
 

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