Using dynamic planning
The idea is: Save the current run result after each calculation
F[I][J] indicates string s[0 I-1] and from the string p[0 J-1] Results of the comparison
First, f[0][0] indicates that two empty strings compare the results to true f[0][0]=true;
Second, when the original string is not empty, no matter what the P-string is the result is true, that is, F[i][0]=false, and when the original string is empty, you need to consider whether P-string p[j-1] is equal to ' * ', when equal to consider p[j-3] whether it has been compared with the empty string is true f[0][j-2]
Finally, the above is the boundary conditions, in the process by judging p[j-1] is ' * ', divided into two situations:
No: Relatively simple, directly compare p[j-1] with s[i-1], or p[j-1] for '. ', and note that you have to add before f[i-1][j-1]
Yes: the first, s[i-1] is the same as the string in front of p[j-3], then f[i][j-2] is OK, the second, the s[i-1] is the same as the p[j-2], plus the previous string f[i-1][j]
1 classSolution {2 Public:3 BOOLIsMatch (stringSstringp) {4 intlens=s.length ();5 intlenp=p.length ();6vector<vector<BOOL>> F (lens+1,vector<BOOL> (Lens,false));7f[0][0]=true;8 for(intI=1; i<=lens;i++)9 {Tenf[i][0]=false; One } A for(intj=1; j<lenp;j++) - { -f[0][j]=j>1&&p[j-1]=='*'&&f[0][j-2]; the } - for(intI=0; i<lens;i++) - for(intj=0; j<lenp;j++) - { + if(p[j-1]!='*') - { +f[i][j]=f[i-1][j-1]&& (p[j-1]==s[i-1]|| p[j-1]=='.'); A } at Else -f[i][j]=f[i][j-2]|| (s[i-1]==p[j-2]||'.'==p[j-2]) &&f[i-1][j]; - } - } -};
Regular Expression Matching