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