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

正则表达式匹配。

记得以前做过通配符匹配的题目,看起来差不多,暂时没有用到更多的RE特性,所以递归算法可以很简洁的解决这个问题。至于效率,总之是过了OJ,但是我估计不高。递归层数至少是N层,如果有*还会更多。我暂时没有想到非递归的方法,Discuss区里有DP的方法,哎,暂时没懂,所以只好交上递归了。

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        if (!*p)    return (!*s);

        if ('*' == *(p + 1)) {
            return (isMatch(s, p + 2) || *s && (*s == *p || '.' == *p) && isMatch(s + 1, p));
        } else {
            if (!*s)    return false;
            return (*s == *p || '.' == *p) ? isMatch(s + 1, p + 1) : false;
        }
    }
};

 

posted @ 2015-01-27 13:26  _Anonyme  阅读(105)  评论(0编辑  收藏  举报