首页 » 编程之美 » 正文

[leetcode_10]Regular Expression Matching

搜索+剪枝,不过有一个很奇怪的地方就是一组测试数据过不了,加了一个针对测试数据的剪枝才AC的。所以,还是应该弄弄DP的方法。 当时一直想用贪心,显然涉及到很多地方的回溯,贪心的方法不好使。 另外注意a* 认为是一体的就是 它代表空,多个a形成的串。

class Solution {
public:
    bool result;
    bool isMatch(const char <em>s, const char *p) {
        // Note: The Solution object is instantiated only once and is reused by each test case.<br />
        result = false;
        int lens = strlen(s);
        int lenp = strlen(p);
        if(p[lenp-1] != '</em>' &amp;&amp; s[lens-1] != p[lenp-1] &amp;&amp; p[lenp-1]!='.')return result;
        matchStep(s,p);
        return result;
    }
private:
    void matchStep(const char * s,const char <em>p) {
        if(result)return;
        if(</em>s == '&#92;&#48;' &amp;&amp; <em>p == '&#92;&#48;') {
            result = true;
            return;
        }
        if(</em>s == '&#92;&#48;') {
            if(<em>(p+1) == '</em>') {
                matchStep(s,p+2);
                return ;
            }
        }
        if(<em>s == '&#92;&#48;' || *p == '&#92;&#48;')return;
        if(</em>(p+1) != '&#92;&#48;') {
            if(<em>(p+1) != '</em>') {
                if(<em>s == *p || *p == '.') {
                    matchStep(s+1,p+1);
                }
                else
                    return;
            }
            else {
                if(</em>s != <em>p &amp;&amp; *p != '.') {
                    matchStep(s,p+2);
                }
                else {
                    matchStep(s,p+2);
                    matchStep(s+1,p);
                    matchStep(s+1,p+2);
                }
            }
        }
        else {
            if(</em>s == *p || *p == '.') {
                matchStep(s+1,p+1);
            }
            else
                return;
        }
    }<br />
};

发表评论