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
题目大意:
'*'代表 前一个字符重复0或若干次。
题目思路:
P[i][j] = P[i - 1][j - 1]
, ifp[j - 1] != '*' && (s[i - 1] == p[j - 1] || p[j - 1] == '.')
;P[i][j] = P[i][j - 2]
, ifp[j - 1] == '*'
P[i][j] = P[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.')
, ifp[j - 1] == '*'
AC代码:
Java:
bool isMatch(string s, string p) {
int m = s.size(), n = p.size();
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] == '*'){ //2.3
dp[i][j] = dp[i][j - 2] ||
(i > 0 && dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'));
}
else{ //1.
if (i > 0 && (s[i-1] == p[j-1] || p[j-1] == '.')){
dp[i][j] = dp[i - 1][j - 1];
}
}
}
}
return dp[m][n];
}
C:
1、考虑特殊情况即*s字符串或者*p字符串结束。
(1)*s字符串结束,要求*p也结束或者间隔‘*’ (例如*p="a*b*c*……"),否则无法匹配
(2)*s字符串未结束,而*p字符串结束,则无法匹配
2、*s字符串与*p字符串均未结束
(1)*(p+1)字符不为'*',则只需比较*s字符与*p字符,若相等则递归到*(s+1)字符串与*(p+1)字符串的比较,否则无法匹配。
(2)*(p+1)字符为'*',则*p字符可以匹配*s字符串中从0开始任意多(记为i)等于*p的字符,然后递归到*(s+i+1)字符串与*(p+2)字符串的比较
bool isMatch(char* s, char* p) {
if (s == NULL || p == NULL) return false;
if (*p == '\0') return *s == '\0';
// ".*" matches "", so we can't check (*s == '\0') here.
if (*(p + 1) == '*')
{
// Here *p != '\0', so this condition equals with
// (*s != '\0' && (*p == '.' || *s == *p)).
while ((*s != '\0' && *p == '.') || *s == *p)
{
if (isMatch(s, p + 2)) return true;
++s;
}
return isMatch(s, p + 2);
}
else if ((*s != '\0' && *p == '.') || *s == *p)
{
return isMatch(s + 1, p + 1);
}
return false;
}