题目
- 请实现一个函数用来匹配包括’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"abaca"匹配,但是与"aa.a"和"ab*a"均不匹配
- leetcode链接:https://leetcode-cn.com/problems/zheng-ze-biao-da-shi-pi-pei-lcof/
代码
/**
* @param {string} s
* @param {string} p
* @return {boolean}
* 无赖写法
*/
var isMatch = function (s, p) {
const reg = new RegExp(`^${p}$`, 'g')
return reg.test(s)
}
/**
* @param {string} s
* @param {string} p
* @return {boolean}
* 动态规划
*/
var isMatch = function (s, p) {
// 1. dp[i][j]表示p的前i个字符是否和s的前j的字符(均包括i,j)是否匹配
// 2.1 不遇到*,当前两个字符相等且dp[i-1][j-1]为true,则dp[i][j] = true
// 2.2 遇到*,原下标字符和*前一个匹配符不相等时,不使用?*,dp[i][j] = dp[i-2][j]
// 2.3 遇到*,原下标字符和*前一个匹配符相等时,不使用?*,dp[i][j] = dp[i-2][j]
// 2.4 遇到*,原下标字符和*前一个匹配符相等时,使用?*,dp[i][j] = dp[i][j-1]
// 3. 初始化:dp[0][0] = true 如果下标i匹配符为*,那么dp[i][0] = dp[i-2][0]
const dp = new Array(p.length + 1)
.fill()
.map(() => new Array(s.length + 1).fill(false))
dp[0][0] = true
for (let i = 1; i <= p.length; i++) {
if (p[i - 1] === '*' && i - 2 >= 0) {
dp[i][0] = dp[i - 2][0]
}
}
for (let i = 1; i <= p.length; i++) {
for (let j = 1; j <= s.length; j++) {
if (p[i - 1] === '*') {
if (i - 2 >= 0) {
if (match(s[j - 1], p[i - 2])) {
dp[i][j] = dp[i - 2][j] || dp[i][j - 1]
} else {
dp[i][j] = dp[i - 2][j]
}
}
} else {
if (match(s[j - 1], p[i - 1]) && dp[i - 1][j - 1]) {
dp[i][j] = true
}
}
}
}
function match(originLetter, regLetter) {
if (regLetter === '.') return true
return originLetter === regLetter
}
return dp[p.length][s.length]
}