题目描述
请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
leetcode对应题目:10. 正则表达式匹配 题目解答
总结:题目的意思是完全匹配所有字符,而不是匹配子串,要分清和KMP的区别。所有在判断的时候一旦发现前面的匹配了,字符串str和pattern都可以向后移动了,而不用向前寻找,再重新匹配。题目中有两个字符'.'和'*'是特殊的,
class Solution {
public:
bool isMatch(string s, string p) {
if(p.empty()) return s.empty();
bool firstmatch = !s.empty() && (s[0] == p[0] || p[0] == '.');
if(p.size() >= 2 && p[1] == '*'){
return isMatch(s,p.substr(2)) || (firstmatch && isMatch(s.substr(1),p));
}
else{
return firstmatch && isMatch(s.substr(1),p.substr(1));
}
}
};
char*避免string的多次拷贝:
class Solution {
public:
bool match(char* str, char* pattern)
{
if(*pattern == '\0') return *str == '\0';
bool first_match = (*str != '\0') && (*str == *pattern || *pattern == '.');
if(*(pattern+1) == '*'){
return match(str,pattern+2) || (first_match && match(str+1,pattern));
}
else{
return first_match && match(str+1,pattern+1);
}
}
};
dp的解法:(转https://leetcode.com/problems/regular-expression-matching/discuss/5684/c-on-space-dp)
We define dp[i][j]
to be true
if s[0..i)
matches p[0..j)
and false
otherwise. The state equations will be:
dp[i][j] = dp[i - 1][j - 1]
, ifp[j - 1] != '*' && (s[i - 1] == p[j - 1] || p[j - 1] == '.')
;dp[i][j] = dp[i][j - 2]
, ifp[j - 1] == '*'
and the pattern repeats for 0 time;dp[i][j] = dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.')
, ifp[j - 1] == '*'
and the pattern repeats for at least 1 time.
i think this sentence:"P[i][j] to be true if s[0..i) matches p[0..j) and false otherwise"
should change to the "P[i][j] will be true if the s[0...i-1]==p[0....j-1]"
class Solution {
public:
bool match(char* str, char* pattern)
{
if(!pattern) return str;
int m = strlen(str),n = strlen(pattern);
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(pattern[j-1] != '*')
dp[i][j] = i && dp[i-1][j-1] && (str[i-1] == pattern[j-1]|| pattern[j-1]=='.');
else{
dp[i][j] = dp[i][j-2]||(i && dp[i-1][j] &&
(str[i-1] == pattern[j-2]||pattern[j-2]=='.'));
}
}
}
return dp[m][n];
}
};