class Solution {
public:
bool isMatch(const char *s, const char *p) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if( 0 == *p) return 0 == *s;
if(*(p+1) != '*')
{
if(*p == *s || (*p) == '.' && (*s) != 0)
{
return isMatch(s+1, p+1);
}
return false;
}
else
{
while(*p == *s || ((*p) == '.' && (*s) != 0))
{
if(isMatch(s, p + 2))
{
return true;
}
s++;
}
return isMatch(s, p + 2);
}
}
};
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
正则表达式匹配,其中.可以表示任意一个字符,*表示零个或者多个前导字符,所谓零个是什么意思呢,给出的例子中,"c*a*b",因为可以表示零个前导字符,因此第一个星号会吃掉字符c,因此等效于"a*b"。这个是不好理解的。还有就是要求两个字符串必须完全匹配,而不是部分匹配。
下面给出一些个人的分析:
因为星号可能会吃掉前一个字符,因此在进行匹配的时候我们不能逐个字符进行匹配,必须先要看后一个字符是什么,如果不是星号我们尽可以逐个匹配,如果两个字符串的第一个相等,我们递归调用就可以逐次判断。这个是好理解的。
关键在于如果后一个字符是星号,我们应该怎么去比较当前位置,以及怎么去调整两个字符串进行比较,因为星号可以替换成零次或者多次当前子字符。这又分为两种情况,第一种就是当前字符不匹配,那么很显然,我们会让星号吃掉当前字符,这样就等于是模式串去掉了前两个字符,这个时候递归调用,即isMatch(s,p+2)。比较难理解的就是当星号前的字符也就是当前字符是匹配的,也会先进行判断isMatch(s,p+2)是否成立,如果成立说明当前星号也要吃掉前一个字符,如果调用判断返回为真说明后面的是匹配s串的,返回为真即可。如果返回为假说明,当前星号可能代表了多个当前字符,因此要对s串逐个向后遍历,其中每增加一个说明星号多代表一个当前字符。这样就能理解下面的代码。
不得不说,这个十几行的代码是优雅的。