Regular Expression Matching

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.