题目描述:
请实现一个函数用来匹配包括’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"abaca"匹配,但是与"aa.a"和"ab*a"均不匹配
思路:此题要求字符串与模式匹配。匹配状态分为三种:1)字符串字符ch和模式字符ch匹配成功;2)字符串ch和模式字符’.‘配对成功;3)字符串字符ch和模式字符"*",这种情况下又分为三种:1、当前字符串和模式字符配对的情况下,将’*'和其前面的字符忽略掉即指针向后移动两位,字符串不移动 2、无视"*"将字符串指针向后移动一位,模式指针向后移动两位 3、字符串向后移动,模式不动
class Solution {
public:
bool match(char* str, char* pattern)
{
if(str==nullptr||pattern==nullptr)
return false;
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||(*pattern=='.'&&(*str!='\0')))//分三种情况
return matchcore(str+1,pattern+2)||matchcore(str,pattern+2)||matchcore(str+1,pattern);
else
return matchcore(str,pattern+2);
}
if(*str==*pattern||(*pattern=='.'&&(*str!='\0')))
return matchcore(str+1,pattern+1);
return false;//其他情况,不匹配
}
};