题目描述
请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
当模式中的第二个字符不是“*”时:
1、如果字符串第一个字符和模式中的第一个字符相匹配,那么字符串和模式都后移一个字符,然后匹配剩余的。
2、如果 字符串第一个字符和模式中的第一个字符相不匹配,直接返回false。
而当模式中的第二个字符是“*”时:
如果字符串第一个字符跟模式第一个字符不匹配,则模式后移2个字符,继续匹配。如果字符串第一个字符跟模式第一个字符匹配,可以有3种匹配方式:
1、模式后移2字符,相当于x*被忽略;
2、字符串后移1字符,模式后移2字符;
3、字符串后移1字符,模式不变,即继续匹配字符下一位,因为*可以匹配多位;
class Solution {
public:
bool match(char* str, char* pattern)
{
if(str==NULL||pattern==NULL) return false;
else
return matchCore(str,pattern);
}
bool matchCore(char*str,char*pattern){
if(*str=='\0'&&*pattern=='\0') return true;
else if(*str!='\0'&&*pattern=='\0') return false;
//else if(*str=='\0'&&*pattern!='\0') return false; "",".",是
if(*(pattern+1)=='*'){
/*
if(*str!=*pattern&&*pattern!='.'){ // "a" ".*" 这种情况始终没有考虑到*str=='\0'的情况
return matchCore(str,pattern+2);
}else{
return matchCore(str,pattern+2)||matchCore(str+1,pattern+2)||matchCore(str+1,pattern);//"bcbbabab",".*a*a"
}*/
if(*pattern==*str||(*pattern=='.'&&*str!='\0'))
return matchCore(str,pattern+2)||matchCore(str+1,pattern);//
else
return matchCore(str,pattern+2);
}else{
if(*str==*pattern||(*pattern=='.'&&*str!='\0')) //"" "."必须要加 *str!='\0',因为str可能已经终止。
return matchCore(str+1,pattern+1);
else
return false;
}
return false;
}
};
/*
补充一点:
而当模式中的第二个字符是“*”时:
1、模式后移2字符,相当于x*被忽略;
2、字符串后移1字符,模式后移2字符;
3、字符串后移1字符,模式不变,即继续匹配字符下一位,因为*可以匹配多位;
情况2可以被情况1和情况3包含。执行一次情况3,再执行一次情况1,就相当于情况2。
代码24行直接删除,也能通过。
再次赞!*/
简洁版代码:
class Solution {
public:
bool match(char* str, char* pattern)
{
if(str==NULL||pattern==NULL)
return false;
else
return matchCore(str,pattern);
}
bool matchCore(char*str,char*pattern){
if(*str=='\0'&&*pattern=='\0') return true;
if(*str!='\0'&&*pattern=='\0') return false;
if(*(pattern+1)=='*'){
if(*pattern==*str||(*str!='\0'&&*pattern=='.'))
return matchCore(str,pattern+2)||matchCore(str+1,pattern);
else
return matchCore(str,pattern+2);
}else{
if(*pattern==*str||(*str!='\0'&&*pattern=='.'))
return matchCore(str+1,pattern+1);
else
return false;
}
}
};