题目:10.RegularExpression Matching
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
题目大意:从p中找到可以匹配s的字符串,如果能找到则返回true,否则返回false
其中:
‘.’匹配任意的单个字符
'*'代表前一个字符重复0或若干次。
思路如下:
(1)*s字符串结束,要求*p也结束或者间隔‘*’则完成匹配;
(2)*s字符串未结束,而*p字符串结束,则无法匹配;
(3)s和p指向的字符串没有结束时,*(p+1)字符为'*',则*p字符可以匹配*s字符串中从0开始任意多个等于*p的字符,然后递归到*(s+i+1)字符串与*(p+2)字符串的比较;
(4)s和p指向的字符串没有结束时,*(p+1)字符不为'*',则只需比较*s字符与*p字符,若(相等或者*p==.)则递归到*(s+1)字符串与*(p+1)字符串的比较;
详细的代码如下:
class Solution {
public:
bool isMatch(const char *s, const char *p) {
//如果s结束了
if (*s == 0)
{
if (*p == 0 || (*(p + 1) == '*' && isMatch(s, p + 2)))
return true;
else
return false;
}
else if (*p == 0)//如果s没有结束p结束了
return false;
if (*(p + 1) != '*')//如果p+1不为*
{
if (*s == *p || *p == '.')
return isMatch(s + 1, p + 1);//匹配下一个
else
return false;
}
else
{
if (*s != *p && *p != '.')
{
return isMatch(s, p + 2);
}
else
{
if (isMatch(s, p + 2))
return true;
int i = 0;
//*p字符可以匹配*s字符串中从0开始任意多个等于*p的元素
while (*(s + i) == *p || *p == '.')
{
if (isMatch(s + i + 1, p + 2))
return true;
if (*(s + i + 1) == 0)
break;
i++;
}
return false;
}
}
}
};