题目10:
(该题目拿到手没什么特别好的思路,从网上看的别人的解法,然后写了下自己的理解,需要常回顾)
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
/* 递归算法 */
int isMatch(char* s, char* p)
{
if (*p == '\0')
{
/* 匹配到最后一个字符,如果s也匹配完则返回true */
return *s == 0;
}
/* 后一个元素不为'*',直接对当前元素进行匹配 */
if (*(p+1) != '*')
{
if (*s != 0 && (*s == *p || *p == '.'))
{
/* 当前元素匹配到 */
return (isMatch(s+1, p+1));
}
else
{
return 0;
}
}
else /* 后一个元素为'*' */
{
/* S: b b b b b a
P: b * a
首先探查到s[0]和p[0],p[1]为'*',先判断前面这个元素是否可以匹配,如果不匹配的话,直接将p[0]和p[1]跳过,将s[0...]和p[2...]进行匹配
如果前面这个元素可以匹配的话,s向后找和s[0]相同的元素,然后去除,和p[2...]匹配,
例子中将bbbba、bbba、bba、ba、a和,a匹配,如果有可以匹配的,则整个s和p可以匹配。
*/
while (*s != 0 && (*s == *p || *p == '.'))
{
if (isMatch(s, p+2))
{
return 1;
}
s++;
}
/* 第一个元素不同,直接将p[0]和p[1]跳过 */
return isMatch(s, p+2);
}
}