Skip to main content

10.js

/** ------------------------------------------------------------------------------
*
* 10. Regular Expression Matching
* Topics: String, Dynamic Programming, Recursion
* https://leetcode.com/problems/regular-expression-matching/description/
*
------------------------------------------------------------------------------ */
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function (s, p) {
const m = s.length
const n = p.length
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(false))
dp[0][0] = true

for (let j = 2; j <= n; j++) {
if (p[j - 1] === "*") dp[0][j] = dp[0][j - 2]
}

for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (p[j - 1] === "." || p[j - 1] === s[i - 1]) {
dp[i][j] = dp[i - 1][j - 1]
} else if (p[j - 1] === "*") {
dp[i][j] = dp[i][j - 2]
if (p[j - 2] === "." || p[j - 2] === s[i - 1]) {
dp[i][j] = dp[i][j] || dp[i - 1][j]
}
}
}
}

return dp[m][n]
}

console.log(isMatch("aa", "a")) // false
console.log(isMatch("aa", "a*")) // true
console.log(isMatch("ab", ".*")) // true
console.log(isMatch("aab", "c*a*b")) // true
console.log(isMatch("mississippi", "mis*is*p*.")) // false
console.log(isMatch("", "")) // true
console.log(isMatch("", "a*")) // true