题目描述:请实现一个函数用来匹配包括’.’和’‘的正则表达式。模式中的字符’.’表示任意一个字符,而’‘表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串”aaa”与模式”a.a”和”ab*ac*a”匹配,但是与”aa.a”和”ab*a”均不匹配。
思路:递归调用的思想,大体分两种情况,即pattern的第二位是* 和不是 *的情况,具体见代码和注释。
代码:
class Solution {
public:
bool match(char* str, char* pattern)
{
if(str==NULL || pattern==NULL)
return false;
return matchcore(str,pattern);
}
bool matchcore(char* str, char* pattern){
//同时到尾说明匹配成功
if(*str=='\0' && *pattern=='\0')
return true;
//pattern到而str没到尾,失败
if(*str!='\0' && *pattern=='\0')
return false;
//如果pattern的第二位是*
if(*(pattern+1)=='*'){
if(*str==*pattern || (*pattern=='.' && *str!='\0')){
return matchcore(str+1,pattern) //匹配到不止一个,对应情况"aabc"和"a*bc"
||matchcore(str,pattern+2) //匹配到0个,但是能进里层这个if的前提说明又不是下面else那种情况,这个比较难想到,"abc"和".*abc",即*匹配到了0个点
||matchcore(str+1,pattern+2); //匹配到1个,"abc"和"a*bc"
}
else
return matchcore(str,pattern+2); //"bc"和"a*bc"
}
//如果pattern的第二位不是*,并且当前位可以匹配上的话,各自后移一位
if(*str==*pattern || (*pattern=='.' && *str!='\0'))
return matchcore(str+1,pattern+1);
return false;
}
};