模式匹配

概述如下:‘.’代表任意字符,‘*’代表前一个字符0或多个,输入一个模式串,一个字符串,返回是否匹配

最初的思路:遍历字符串,遇上‘.’,跳过到下一位置,遇上‘*’则先统计字符串的重复个数count1,然后统计‘*’后的相同字符的重复个数count2,如果count1>=count2的情况下,是可以继续的

如果*前的字符与字符串当前位置一致,且大于等于的情况成立,则跳到下一个位置,否则,跳过(+2)。但是这里出现了很多情况,比如,首先要统计count的时候会发现需要考虑到数组或者说字符串的边界问题,

程序很容易报错,然后就是if语句的使用过多,容易造成逻辑错误,总之是麻烦并且容易出错。

认可的思路:首先还是分情况,两个字符数组的指针同时移动,如果模式串当前指针是‘.’则跳过;如果当前指针的下一个指针是‘*’,那么有几种状态:

1)模式串当前字符与字符串当前字符不一致,模式串直接跳过,字符串状态不变;

2)模式串当前字符与字符串当前字符相同,模式串状态不变,字符串向右移动一位;

3)模式串当前字符与字符串当前字符相同,模式串向右两位(跳过),字符串向右移动一位。

4)模式串当前字符与字符串当前字符相同,模式串直接跳过,字符串状态不变;  --这里是因为ch*不起作用,否则不匹配

5)模式串当前字符是‘.’,重复1)2)3)过程。

代码如下:

class solution
{
public:
    bool match_string(char *str,char *pattern)
    {
        if(str==nullptr||pattern==nullptr)
            return false;
        return match_string_core(str,pattern);
    }
    bool match_string_core(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 match_string_core(str+1,pattern)||match_string_core(str+1,pattern+2)||match_string_core(str,pattern+2);
            else
                return match_string_core(str,pattern+2);
        }
        if(*pattern=='.'||*str==*pattern)
            return match_string_core(str+1,pattern+2);
        return false;
    }
};

猜你喜欢

转载自www.cnblogs.com/jianbo1995/p/9874594.html
今日推荐