标签:
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
bool backTracking(char* s, char* p, int p1, int p2, bool pointStar){ while(p[p2] != ‘\0‘){ if(p[p2] == ‘*‘){ if(backTracking(s,p,p1-1,p2+1,false)) return true; //* stands for 0 times while(s[p1]!= ‘\0‘){ if(backTracking(s,p,p1,p2+1,pointStar)) return true; //* stands for 1,2,... times if(pointStar || p[p2-1] == s[p1]) p1++; else return false; } if(p[p2+1] == ‘\0‘) return true; else return false; } pointStar = false; if(s[p1] == p[p2]){ printf("s=%d, p = %d\n", s[p1],p[p2] ); p1++; p2++; if(p[p2] == ‘*‘){ //if a* occurs while(p[p2+1]==p[p2-1] && p[p2+2]==‘*‘) p2+=2; //neglect following a* } } else if(p[p2] == ‘.‘ ){ if(s[p1] == ‘\0‘ && p[p2+1] != ‘*‘) return false; p1++; p2++; if(p[p2] == ‘*‘){ //if .* occurs while(p[p2+1]==‘.‘ && p[p2+2]==‘*‘) p2+=2; //neglect following .* pointStar = true; } } else if(p[p2+1] == ‘*‘){ p2+=2; } else return false; } if(s[p1] == ‘\0‘) return true; else return false; } bool isMatch(char* s, char* p) { return backTracking(s,p,0,0, false); }
10. Regular Expression Matching
标签:
原文地址:http://www.cnblogs.com/qionglouyuyu/p/5366402.html