leedcode 10. 正则表达式匹配
递归解法,时间复杂度比较高,后面要尝试改成动规
bool end_or_not(string p) { for(int i=0;i<p.size();i+=2) { if(((p[i]>='a'&&p[i]<='z')||p[i]=='.')&&p[i+1]=='*') continue; return false; } return true; } bool check(string s, string p) { int donser[27]; memset(donser,0,sizeof(donser)); for(int i=0;i<p.size();i++) { if(p[i]=='.'||p[i]=='*') continue; if(donser[p[i]-'a']==0) { donser[p[i]-'a']=1; int lable=0; if(p[i+1]=='*') continue; for(int j=0;j<s.size();j++) { if(s[j]==p[i]) { lable=1; break; } } if(lable==0) return false; } } return true; } class Solution { public: bool isMatch(string s, string p) { int ptr_s=0,ptr_p=0; bool x=0; char now=p[ptr_p],next=p[ptr_p+1]; if(check(s,p)==false) return false; if(s[ptr_s]=='\0') { return end_or_not(p.substr(ptr_p,p.size()-ptr_p)); } if(p[ptr_p]=='\0') return false; if((now>='a'&&now<='z'&&next!='*')||(now=='.'&&next!='*')) { if(s[ptr_s]==p[ptr_p]&&s[ptr_s+1]=='\0'&&p[ptr_p+1]=='\0') return true; if(s[ptr_s]==p[ptr_p]||(now=='.'&&next!='*')) { ptr_s++; ptr_p++; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_s--; ptr_p--; if(x==true) return true; } else { return false; } } if(now=='.'&&next=='*') { ptr_p+=2; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_p-=2; if(x==true) return true; ptr_s++; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_s--; if(x==true) return true; } if(now>='a'&&now<='z'&&next=='*') { if(s[ptr_s]!=p[ptr_p]) { ptr_p+=2; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_p-=2; if(x==true) return true; } else { ptr_p+=2; ptr_s++; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_p-=2; ptr_s--; if(x==true) return true; ptr_s++; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_s--; if(x==true) return true; ptr_p+=2; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_p-=2; if(x==true) return true; } } return false; } };
来源:https://www.cnblogs.com/dzzy/p/12274354.html