10.Regular Expression Matching[Hard]
Description
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).
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
Solution
动态规划Tag里的题目,但是我第一反应是用递归做,所以就试了试递归,居然能AC。
递归:
分情况讨论,p为空直接返回。
p为1就比较第一个,可以相等可以为‘.’。
由于’*’匹配一个或多个在它之前的字符,若p的第二个字符为’*’,s不为空且第一个字符匹配,调用递归函数匹配s和去掉前两个字符的p,若匹配返回true,否则s去掉首字母(已经匹配好的)再和pattern比较。
若不为’*’,就都去掉第一个字符然后递归。
动态规划:
自己是没想出什么好方法,看到discuss有一个说的不错,直接搬运。
Easy DP Java Solution with detailed Explanation
Complexity analysis
O(M*N)
M = s.length()
N = p.length()
Code
(1)递归
class Solution {
public:
bool isMatch(string s, string p) {
if (p.empty()) return s.empty();
if (p.size() == 1) {
return (s.size() == 1 && (s[0] == p[0] || p[0] == '.'));
}
if (p[1] != '*') {
if (s.empty()) return false;
return (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1));
}
while (!s.empty() && (s[0] == p[0] || p[0] == '.')) {
if (isMatch(s, p.substr(2))) return true;
s = s.substr(1);
}
return isMatch(s, p.substr(2));
}
};
(2)动态规划
class Solution {
public:
bool isMatch(string s, string p) {
int M = s.length(), N = p.length();
vector<vector<bool> > dp(M + 1, vector<bool> (N + 1, false));
dp[0][0] = true;
for (int i = 0; i <= M; i++)
for (int j = 1; j <= N; j++)
if (p[j - 1] == '*')
dp[i][j] = dp[i][j - 2] || (i > 0 && (s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]);
else dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
return dp[M][N];
}
};