题目描述
请实现一个函数用来匹配包括’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab* ac* a"匹配,但是与"aa.a"和"ab*a"均不匹配
解决方法
class Solution {
public:
/*当模式中的第二个字符不是“*”时:
1、如果字符串第一个字符和模式中的第一个字符相匹配,那么字符串和模式都后移一个字符,然后匹配剩余的。
2、如果字符串第一个字符和模式中的第一个字符相不匹配,直接返回false。
而当模式中的第二个字符是“*”时:
1、如果字符串第一个字符跟模式第一个字符不匹配,则模式后移2个字符,继续匹配。
2、如果字符串第一个字符跟模式第一个字符匹配,可以有3种匹配方式:
(1)字符串不变,模式后移2个字符;
(2)字符串后移1字符,模式后移2字符;
(3)字符串后移1字符,模式不变,即继续匹配字符下一位,因为*可以匹配多位;*/
bool match(char* str, char* pattern)
{
bool result=false;
if(!str||!pattern)
return result;
result=matchcore(str,pattern);
return result;
}
bool matchcore(char* str,char* pattern)
{
if(*str == '\0'&& *pattern == '\0')//所有字符匹配整个模式,仅仅此一种情况返回为真
return true;
if(*(pattern+1)=='*')
{
if(*pattern == *str||(*pattern=='.'&& *str !='\0'))
return matchcore(str,pattern+2)||matchcore(str+1,pattern+2)||matchcore(str+1,pattern);
else
return matchcore(str,pattern+2);
}
if(*pattern == *str || (*pattern == '.' && *str!='\0'))//正常情况下,两者相等
return matchcore(str+1,pattern+1);
return false;
}
};