1.正则表达式匹配
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/regular-expression-matching
思路一:递归匹配
class Solution {
public:
bool isMatch(string s, string p) {
return match(s.data(), p.data());//转化为字符数组
}
bool match(char* s, char* p) {
if(*s=='\0'&&*p=='\0') return true;//目的是先把s匹配完
if(*s!='\0'&&*p=='\0') return false;
if(*(p+1)!='*')
{
if(*s==*p||(*s!='\0'&&*p=='.'))
{
return match(s+1,p+1);////直接匹配,如果二者相等或str不为空,pattern为.则成功
}
else
{
return false;
}
}
else
{
if(*s==*p||(*s!='\0'&&*p=='.'))
{
return match(s, p+2) || match(s+1, p);//当*匹配一个或多个字符(aaa a*多个) (aaa a*aa一个)
}
else
{
return match(s,p+2);//当*匹配0个字符时,ba与a*ba
}
}
}
};
京公网安备 11010502036488号