Implement regular expression matching with support for ‘.’ and ‘*’.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
如果p当前是*号,则可以匹配一个或多个上一个字符,否则各自往后移动一个位置,然后再递归的去判断剩余的部分
递归解法如下
1 | class Solution { |
若S的前i个字符与P的前j个字符已经匹配,则只需考察剩余的字符即可,由于具有无后效性,故也可采用动态规划解法
1 | dp[i][j] 表示s[0, i-1] 和 p[0, j-1]是否匹配 |
1 | class Solution { |