/** * @param {string} s * @param {string} p * @return {boolean} */ var isMatch = function(s, p) { let dp = []; let len = s.length; let _len = p.length; for(let i = 0; i <= len; i++){ dp.push([]); dp[i][0] = 0; } dp[0][0] = 1; for(let i = 0; i <= _len; i++){ if(p.charAt(i) === ‘*‘ && dp[0][i - 1]){ dp[0][i + 1] = 1; }else{ dp[0][i + 1] = 0; } } for(let i = 0; i < len; i++){ for(let j = 0; j < _len; j++){ if((s.charAt(i) === p.charAt(j) || p.charAt(j) === ‘.‘) && dp[i][j]){ dp[i + 1][j + 1] = 1; }else if(p.charAt(j) === ‘*‘ && (dp[i + 1][j] || dp[i][j + 1]) && (s.charAt(i) === p.charAt(j - 1) || p.charAt(j - 1) === ‘.‘)){ dp[i + 1][j + 1] = 1; }else if(p.charAt(j) === ‘*‘ && dp[i + 1][j - 1]){ dp[i + 1][j + 1] = 1; }else{ dp[i + 1][j + 1] = 0; } } } return dp[len][_len]; };
如果 p.charAt(j) == s.charAt(i) : dp[i][j] = dp[i-1][j-1];
如果 p.charAt(j) == ‘.‘ : dp[i][j] = dp[i-1][j-1];
如果 p.charAt(j) == ‘*‘:
如果 p.charAt(j-1) != s.charAt(i) : dp[i][j] = dp[i][j-2] //in this case, a* only counts as empty
如果 p.charAt(i-1) == s.charAt(i) or p.charAt(i-1) == ‘.‘:
dp[i][j] = dp[i-1][j] //in this case, a* counts as multiple a
or dp[i][j] = dp[i][j-1] // in this case, a* counts as single a
or dp[i][j] = dp[i][j-2] // in this case, a* counts as empty
来自乔碧萝殿下?的题解
原文地址:https://www.cnblogs.com/qq965921539/p/12283924.html
时间: 2024-10-05 08:40:53