题目描述:
Given an input string s and a pattern p, implement regular expression matching with support for ’ . ’ and ‘ * ‘ where:
‘.’ Matches any single character.
‘*’ Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Example 1:
Input: s = “aa”, p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.
Example 2:
Input: s = “aa”, p = “a*”
Output: true
Explanation: ‘*’ means zero or more of the preceding element, ‘a’. Therefore, by repeating ‘a’ once, it becomes “aa”.
Example 3:
Input: s = “ab”, p = “."
Output: true
Explanation: ".” means “zero or more (*) of any character (.)”.
Example 4:
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”.
Example 5:
Input: s = “mississippi”, p = “mis * is * p *”
Output: false
Constraints:
0 <= s.length <= 20
0 <= p.length <= 30
s contains only lowercase English letters.
p contains only lowercase English letters, ‘.’, and ’ * '.
It is guaranteed for each appearance of the character ‘*’, there will be a previous valid character to match.
Time complexity: O(nm)
动态规划:
状态表示:dp[i][j]表示s的前i了字母是否能匹配p的前j个字母
状态转移:
如果p[j]不是通配符 ’ * ‘,则当且仅当s[i]可以和p[j]匹配,且dp[i-1][j-1]是真, 则dp[i][j]是真;
如果p[j]是通配符’ * ',则有下面的两种情况:
- 字符s[i] != p[j-1]: 在这种情况下 p[j-1]p[j] 可以看作是 空字符 则:dp[i][j] = dp[i][j-2]
- 字符s[i] == p[j-1] 或者 p[j-1] == ‘.’ 把p[j-1]假设为字符a,则:
(1) dp[i][j] = dp[i-1][j] a* 可以匹配多个字符串 aaaa
(2) dp[i][j] = dp[i][j-1] a* 可以匹配单个字符 a
(3) dp[i][j] = dp[i][j-2] a* 可以匹配空字符
注意在 初始化dp时 因为 通配符’ * '加上它的前一个字符匹配空字符,所以要先初始化所有p的所有偶数长度的子符串
class Solution {