正则

125 阅读1分钟
function match(s, p) {
    var sArray = s.split('');
    var pArray = p.split('');
    var result = [];
    var path = [];
    var lastIndex = 0;
    function isMacth(index) {
        var matchitem = pArray[index];
        
        //console.log(matchitem)
        if (matchitem == '.') {
            path.push(sArray.shift())
            return true;
        }
        if (matchitem == '*') {
            //  debugger
            do {
                
                if (sArray[0] !== path[path.length - 1] && pArray[index - 1] !== '.') {
                    break;
                } else {
                    path.push(sArray.shift());
                }
            } while (sArray.length > 0);
            return true;
        }
        if (matchitem == sArray[0]) {
            path.push(sArray.shift())
            return true;
        }
        if (pArray[index + 1] == '*') {
            return true;
        }
        return false;

    }
    function backtracking(s, p, index) {
        if (sArray.length==0) {
            if(index>=pArray.length){
                lastIndex = index;
                return;
            }else{
                //debugger
                sArray = path.splice(index);
                //backtracking(s,p,index+1)
            }
            
      
        }
        const match = isMacth(index)
        if (match) {
            backtracking(s, p, index+1);
        }
    }
    backtracking(s, p, 0);
    const paths = path.join('')
    console.log(paths, lastIndex)
    return paths.length === s.length && lastIndex!==0;
}



console.log(match('smissip', 'smis*ip'))
console.log(match('sbb', '.*'))
console.log(match('aab', 'c*d*a*b'))
console.log(match("mississippi", "mis*is*p*."))
console.log(match('ab', '.*'))
console.log(match("ab", ".*c"))
console.log(match("aaa", "a*a"))