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


class Solution {
public:
    bool isMatch(const char *s, const char *p) 
    {
        int lens=strlen(s);
        int lenp=strlen(p);
        bool* check=new bool[lens+1];
        check[0]=true;
        for(int j=1;j<=lens;j++)
            check[j]=false;

        for(int i=0;i<lenp;i++)
        {
            if(p[i]!='*' && p[i+1]!='*' && p[i]!='.')
            {
                for(int j=lens;j>=0;j--)
                    check[j]=check[j-1] && (p[i]==s[j-1]);                
            }
            if(p[i]=='.' && p[i+1]!='*')
            {
                for(int j=lens;j>=0;j--)
                    check[j]=check[j-1];                
            }
            if(p[i+1]=='*')
            {
                char c=p[i];                
                if(c=='*')
                    for(int j=1;j<=lens;j++)
                        check[j]=true;
                else if(c=='.')
                {
                    //find the first match
                    int j=0;
                    while(check[j]==false && j<=lens) j++;
                    //then all the next match 
                    if(j<=lens)
                        for(;j<=lens;j++)
                            check[j]=true;
                }
                else    for(int j=1;j<=lens;j++)
                        if(check[j-1] && c==s[j-1])
                            check[j]=true;
                i++;
            }    
            check[0]=check[0] && (p[i]=='*');
        }
        return check[lens];
    }
};
原文地址:https://www.cnblogs.com/erictanghu/p/3759224.html