JSFiddle - React, Tailwind, and code Playground

by eelyafi

JavaScript

/*
 Question was "Given a pattern and a string input - find if the string follows the same pattern and return 0 or 1.
 Examples:
 1) Pattern : "abba", input: "redbluebluered" should return 1.
 2) Pattern: "aaaa", input: "asdasdasdasd" should return 1.
 3) Pattern: "aabb", input: "xyzabcxzyabc" should return 0.
 */
function isMatch(str, iStr, ptn, iPtn, hmap){

    if(iStr == str.length && iPtn == ptn.length) {
        return true;
    }
    if (iStr == str.length || iPtn == ptn.length) {
        return false;
    }

    //debugger;
    var c = ptn[iPtn];

    if (hmap[c]) {
        //console.log(hmap[c], 'hmap[c]');
        var toMatch = hmap[c];
        for (var i = 0; i < toMatch.length; i++) {

            if (iStr >= str.length || str[iStr] != toMatch[i]) {
                return false;
            }

            iStr++;
        }
        return isMatch(str, iStr, ptn, iPtn+1, hmap);
    } else {
        //try all possiblities
        var flag = false;
        for (var i = iStr; i < str.length; i++){
            hmap[c] = str.slice(iStr, i + 1);

            console.log(hmap[c], c, hmap, 'hmap[c]');

            flag = flag || isMatch(str, i + 1, ptn, iPtn + 1, hmap);
            delete hmap[c];
            if (flag) {
                return true;
            }
        }
    }


    return false;
}

function match(str, ptn){
    str = str.split('');
    ptn = ptn.split('');

    if (str.length < ptn.length) {
        return false;
    }

    if (!ptn) {
        return !str ? true : false;
    }
    if (ptn.length ==1 ) {
        return  str.length > 1 ? true : false;
    }

    return isMatch(str, 0, ptn, 0, {});
}



console.log(match('redbluebluered', 'abba'));