LeetCode 10. 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

Subscribe to see which companies asked this question.

题目意思就是模拟一个简单的正则表达式。
整个匹配过程只有两种情况

设匹配串为s, 被匹配串为p;

  • p下一步是 '*'。
  • p下一步不是'*'。
class Solution {
    
    bool Match(size_t a, size_t b, const string &s, const string &p)
    {
        if(b == p.size())
            return a == s.size();
        
        if(b+1 < p.size())
        {
            if(p[b+1] != '*')
            {
                if(s[a] == p[b] || p[b] == '.')
                    return Match(a+1, b+1, s, p);
                else
                    return false;
            }
            else
            {
                while(a < s.size() && (p[b] == s[a] || p[b] == '.'))
                {
                    if(Match(a, b+2, s, p))
                        return true;
                    a ++;
                }
                return Match(a, b+2, s, p);
            }
        }
        else
        {
            if(s[a] == p[b] || p[b] == '.')
                return Match(a+1, b+1, s, p);
            else
                return false;
        }
    }
public:
    bool isMatch(string s, string p) {
        return Match((size_t)0, (size_t)0, s, p);
    }
};
posted @ 2017-03-18 10:12  aiterator  阅读(90)  评论(0编辑  收藏  举报