LeetCode OJ: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

正则表达式的匹配,注意*代表的不是任意的字符,而是0个或者任意多个前向的字符,代码如下:

 1 class Solution {
 2 public:
 3     bool isMatch(string s, string p) {
 4            if(p.size() == 0) return s.size() == 0;
 5            if(p[1] != '*'){
 6                if(s.size() != 0 && (p[0] == s[0] || p[0] == '.')) 
 7                    return isMatch(s.substr(1), p.substr(1));
 8                return false;
 9            }else{
10                while(s.size() != 0 &&(s[0] == p[0] || p[0] == '.')){//模式串匹配0个或者更多的字符
11                    if(isMatch(s, p.substr(2)))
12                        return true;
13                    s = s.substr(1);
14                }
15                return isMatch(s, p.substr(2));
16            }
17     }
18 };

 

posted @ 2015-11-23 22:04  eversliver  阅读(419)  评论(0编辑  收藏  举报