LeetCode "Regular Expression Matching"

It took me numerous submissions to get AC.... until I checked this article:

http://leetcode.com/2011/09/regular-expression-matching.html

Very clean idea. Again, think crystal clean before you code!!

class Solution {
public:
    struct Rec
    {
        Rec(char cc, bool bStar) : c(cc), star(bStar) {}
        char c;
        bool star;
    };
    bool _isMatch(string &s, int i0, vector<Rec> &dict, int i1)
    {        
        if(i1 == dict.size()) return i0 == s.length();

        char c = s[i0];
        Rec &r = dict[i1];
        if (!r.star)    //    Not Star
        {
            return (c == r.c || r.c == '.') && _isMatch(s, i0 + 1, dict, i1 + 1);
        }
        // star
        while(c == r.c || r.c == '.')
        {
            if (_isMatch(s, i0, dict, i1 + 1)) return true;
            if(i0 < s.length())
                c = s[++ i0];            
            else break;
        }
        //     even not match star?
        return _isMatch(s, i0, dict, i1 + 1);
    }
    bool isMatch(const char *s, const char *p) {
        int len1 = strlen(s);
        int len2 = strlen(p);
        if(len1 == 0 && len2 == 0) return true;
        if(len2 == 0) return false;

        //    Build pattern
        vector<Rec> dict;
        for(size_t i = 0; i < len2; i ++)
        {
            char c = *(p + i), nc = 0;
            if(c == '*')
            {                
                continue;
            }
            
            if((i + 1) < len2)    nc = *(p + i + 1);
            dict.push_back(Rec(c, nc == '*'));
        }
        if(len1 == 0)
        {
            int i = 0;
            while(i < dict.size())
                if(!dict[i++].star) return false;
            return true;
        }
        string str(s);
        return _isMatch(str, 0, dict, 0);
    }
};
原文地址:https://www.cnblogs.com/tonix/p/3906320.html