借鉴了网上的答案,觉得这个解法的思维比较清晰,比较容易理解。 大致就是递归判断当前pattern的第二个字符是否是*,不是的话比较当前s和p的第一个字符是否相同。若是*的话,则要考虑两种情况,1.s在匹配p的第一个字符时s++ 2.考虑当前的s和p+2的匹配情况。
class Solution {
public:
bool isMatch(const char *s, const char *p) {
if( *p == 0 )
{
if( *s == 0 )
return true;
else
return false;
}
if( *(p+1) != '*' )
{
if( *s != 0 && ( *s == *p || *p == '.') )
{
return isMatch(s+1,p+1);
}
else
{
return false;
}
}
else
{
while( *s != 0 && ( *s == *p || *p == '.') )
{
if(isMatch(s,p+2) == true )
return true;
s++;
}
}
return isMatch(s,p+2);
}
};