剑指offer——53/66正则表达式匹配

请实现一个函数用来匹配包括‘.’和‘*’的正则表达式,模式中的字符‘.’表示任意一个字符,而‘*’表示它前面的字符可以出现任意多次(包含0次),在本题中,匹配是指字符串的所有字符匹配整个模式,例如字符串“aaa”与模式“a.a”和“ab*ac*a”匹配,但是与“aa.a”和“ab*a”均不匹配。

class Solution {
public:
    bool match(char* str, char* pattern)
    {
        if(str==nullptr||pattern==nullptr)
            return false;
        int i=0;
        int j=0;
        return matchCore(str,pattern,i,j);
    }
    bool matchCore(char *str,char *pattern,int i,int j)
    {
        int li=strlen(str);
        int lj=strlen(pattern);
        if(i==li&&j==lj)
            return true;
        if(i!=li&&j==lj)
            return false;
        if(j+1<lj&&pattern[j+1]=='*')
        {
            if(i!=li&&(pattern[j]==str[i]||pattern[j]=='.'))
                return matchCore(str,pattern,i,j+2)||
                matchCore(str,pattern,i+1,j+2)||
                matchCore(str,pattern,i+1,j);
            else
                return matchCore(str,pattern,i,j+2);
        }
        if(i!=li&&(pattern[j]==str[i]||pattern[j]=='.'))
            return matchCore(str,pattern,i+1,j+1);
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_17141957/article/details/81066478