"Regular Expression Matching" cpp

Source: Internet
Author: User

Topic:

Implement regular expression matching with support for ‘.‘ and ‘*‘ .

‘.‘ Matches any single character. ' * ' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). The function prototype should be:bool IsMatch (const char *s, const char *p) Some examples:ismatch ("AA", "a") →falseismatch ( "AA", "AA") →trueismatch ("AAA", "AA") →falseismatch ("AA", "A *") →trueismatch ("AA", ". *") →trueismatch ("AB", ". *") →true IsMatch ("AaB", "C*a*b") →true

Code:

classSolution { Public:    BOOLIsMatch (stringSstringp) {//both S and P reach their ends        if(P.empty ())returnS.empty (); //P ' s next is not *        if(p[1]!='*' )        {            return(s[0]==p[0] || (p[0]=='.'&&!s.empty ()) && Solution::ismatch (S.substr (1), P.substr (1)); }        //P ' s next is * and Curr s match curr P        inti =0;  for(; s[i]==p[0] || (p[0]=='.'&& i<s.size ()); ++i) {if(Solution::ismatch (S.substr (i), P.substr (2)) )return true; }        //P ' s next is * but Curr s not match Curr P        returnSolution::ismatch (S.substr (i), P.substr (2)); }};

Tips

This code is leetcode on the latest interface, which is AC-capable.

The idea is somewhat complex: the main judgment is whether the next p is *, and the classification is discussed.

Although the code is AC, some doubts still exist:

1. p[1]!= ' * ' this statement will encounter P[1] does not exist (index out of bounds), the result returned on my Mac is nul, but OJ can pass.

2. P.SUBSTR (2) This statement also encounters the same problem as 1.

Although the OJ passed, there are also various border hazards. If the string index is out of bounds, it should raise undefined behavior, but I don't know why.

Use DP to do it again and see if the boundary conditions can be simplified.

"Regular Expression Matching" cpp

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.