Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Note:
- s could be empty and contains only lowercase letters a-z.
- p could be empty and contains only lowercase letters a-z, and characters like . or *.
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".
Input: s = "mississippi" p = "mis*is*p*." Output: false
思路:
两个字符串匹配类问题,通常使用匹配型动态规划。
一般动态解题步骤:
1. 确定状态
dp[i][j]表示前i个p字符与前j个s字符是否匹配
2. 转移方程
因为存在'.'和'*'两个特殊字符,需要分类讨论:
- 如果p[j - 1]不是'*', 那只要s与p当前字符相同或者p的当前字符为'.', 因为'.'可以匹配任何非空单个字符, 即dp[i][j] = dp[i - 1][j - 1] and (s[i - 1] == p[j - 1] or p[j - 1] == '.')
- 如果p[j - 1]是'*', 可以分两种情况讨论:1. x*匹配0个字符,dp[i][j] = dp[i][j - 2]; 2. x*匹配1-N个字符,p的前一字符与当前s字符相同,并且上一字符串是匹配的(dp[i -1][j]), dp[i][j] = dp[i][j- 2] or (s[i - 1] == p[j - 2] or p[j - 2] == '.' and dp[i - 1][j])
3. 初始条件和边界条件
dp[0][0] = True # 空字符串可以匹配空字符串
对于第一行的处理,dp[0][j] = dp[0][j - 2] if p[j - 1] == '*' else False
4. 计算顺序
i: 1 - len(s)
j: 1 - len(p)
class Solution:
def isMatch(self, s: str, p: str) -> bool:
rows = len(s)
columns = len(p)
dp = [[False for _ in range(columns + 1)] for _ in range(rows + 1)]
dp[0][0] = True
# 初始化第一行
for column in range(1, columns + 1):
if p[column - 1] == "*":
dp[0][column] = dp[0][column - 2]
for r in range(1, rows + 1):
for c in range(1, columns + 1):
if p[c - 1] == '*':
dp[r][c] = dp[r][c - 2] or ((s[r - 1] == p[c - 2] or p[c - 2] == '.') and dp[r - 1][c])
else:
dp[r][c] = dp[r - 1][c - 1] and (s[r - 1] == p[c - 1] or p[c - 1] == '.')
return dp[-1][-1]