剑指offer:正则表达式匹配

题目描述

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

思路

//字符串和模式光标都走到最后说明匹配结束,如果模式到了最后,字符串没匹配完则匹配失败,如果中间有不匹配的也是失败
//如果模式字符后一位是*,而且当前字符匹配模式或者模式当前位为‘.’,则可能这个X*用多次或者一次不用,
//return matchCore(str+1,pattern)||matchCore(str,pattern+2)
//如果不匹配,则说明X*不用直接return  matchCore(str,pattern+2),
//如果模式下一位不是*,且当前位等于模式,或者字符不到结尾,模式为‘.’则说明匹配了当前位置
//,return matchCore(str+1,pattern+1);

code

class Solution {
public:
    bool match(char* str, char* pattern)
    {
        if(str==nullptr||pattern==nullptr)
            return false;
        return matchCore(str,pattern);
    }
    bool matchCore(char*str,char*pattern){
        if(*str=='\0'&&*pattern=='\0')
            return true;
        if(*str!='\0'&&*pattern=='\0')
            return false;
        if(*(pattern+1)=='*'){
            if(*str==*pattern||(*pattern=='.'&&*str!='\0')){
                return matchCore(str+1,pattern)||matchCore(str,pattern+2);
            }else{
                return  matchCore(str,pattern+2);
            }
        }
        if(*pattern==*str||(*str!='\0'&&*pattern=='.'))
            return matchCore(str+1,pattern+1);
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_33278461/article/details/80232519