Ten. Regular Expression Matching

Source: Internet
Author: User

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") →false
IsMatch ("AA", "AA") →true
IsMatch ("AAA", "AA") →false
IsMatch ("AA", "A *") →true
IsMatch ("AA", ". *") →true
IsMatch ("AB", ". *") →true
IsMatch ("AaB", "C*a*b") →true

Method I: Backtracking method. The next character is * to be backtrack.

classSolution { Public:    BOOLIsMatch (stringSstringp) {returnDfsismatch (S,p,0,0); }        BOOLDfsismatch (Const string& S,Const string& P,intSindex,intpindex) {        if(P[pindex] = =' /')//End Condition: s if ' + ', p must also '            returnS[sindex] = =' /'; if(p[pindex+1] =='*') {            /*'. ' means any character (except ' ") * '. ' means repeat 0 or more times * '. * ' means repeat ‘.‘ 0 or more times*/              while((S[sindex]! =' /'&& P[pindex] = ='.') || S[sindex] = = P[pindex]) {//'. ' can match any character except '                if(Dfsismatch (S, p, Sindex, pindex+2))//P[pindex] Repeat 0 times                    return true; Sindex+=1;//P[pindex] Repeat number of times on the original basis +1            }                        returnDfsismatch (S, p, Sindex, pindex+2);//When s[sindex]! = P[pindex] && p[pindex]! = '. ' (May return True if only s[sindex]==p[pindex]== ')        }         Else if((S[sindex]! =' /'&& P[pindex] = ='.') || S[sindex] = =P[pindex]) {            returnDfsismatch (S, p, Sindex +1, Pindex +1); }               return false; }};

Method II: Dynamic Programming. Set the two-bit array dp[i][j] to represent two string state relationships, Dp[i][j]=true, representing s[0..i] matches the result of P[0..J].

Ten. 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.