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個或者任意多個前向的字符,代碼以下:express

 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 };
相關文章
相關標籤/搜索