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") → 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

假设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 };

 

 

posted on 2014-09-15 20:45  bug睡的略爽  阅读(189)  评论(0编辑  收藏  举报

导航