首页 > 代码库 > Regular Expression Matching

Regular Expression Matching

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", ".*") → trueisMatch("aab", "c*a*b") → true

假设s串为s[0...n-1],p串为p[0...m-1],已经匹配了s[0..i-1],p[0...j-1],
这是需要判断p[j]及p[j+1]的情况
1. p[j+1]不为‘*‘的时候,那么只需要判断s[i]与p[j]是否相同或p[j]是否是‘.‘,如果满足上述要求,继续匹配下一个子串s[i+1...n-1]和p[j+1...m-1],否则匹配不成功
2. p[j+1]是‘*‘,由于 a* 表示a有0个或多个,.*表示任意字符有0个或多个,因此需要递归0个,1个,2个等等直到s串中最多满足a*
 1 class Solution { 2 public: 3     bool isMatch(const char *s, const char *p) { 4         if( !*p ) return *s == 0;   //若全部都匹配完成,则返回真 5         if( *(p+1) == * ) {   //p下一个字符为‘*‘ 6             while( *s && ( *s == *p || *p == . ) ) {  //*s=*p或*p=‘.‘的时候 7                 if( isMatch(s, p+2) ) return true; 8                 ++s;    //开始递增,以处理a*满足0个或1个或2个。。。。的条件 9             }10             return isMatch(s, p+2); //a*已经被匹配完,*s!=*p,继续进行下一个匹配11         }12         else if( *s && ( *s == *p || *p == . ) )  //p下一个字符不为‘*‘的匹配情况13                 return isMatch( s+1, p+1 );14         return false;15     }16 };

 

 

Regular Expression Matching