剑指Offer——19 正则表达式匹配

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Lollipop66/article/details/81062047
之前做这个题的时候特别凌乱,但这次会好很多,把思路分享出来,以及边界的确定
​思路:我们用俩个索引来控制字符串和模式串已经匹配到达的位置,index1和index2,
​ 这个问题就难在有*的位置,我们需要考虑下一个位置为*时候怎么处理
​ 1.模式串的index2下一个位置为*
​ 1)字符串的index1位置与模式串index2位置是匹配的或者index2位置为.
​ (1)index2位置字符出现0次
​ 或者(2)index2位置字符出现大于0次
​ 2)字符串的index1位置与模式串index2位置是不匹配的
​ index2当前位置的字符出现0次
​ 2.模式串的index2下一个位置不为*
​ 1)字符串index1与模式串index2位置匹配或者index2位置为 . ,向下一个位置遍历
​ 2)否则返回false;

​以上是大体的思路,但是细节还需要考虑,我们这个题需要用递归去做,那么需要考虑递归出口,
​1.模式串和字符串均到末尾,直接返回true
​2.模式串到末尾,字符串没有到末尾,直接返回false
​3.还有一种就是字符串到末尾,模式串没有到末尾,这里我们直接把他放进具体情况去考虑

​具体情况中,当需要判断index1位置与index2位置进行判断匹配的时候,我们需要判断index1是否
​达到末尾,如果没有达到就跟最上面写的伪代码一样,如果到达末尾了,就需要仔细考虑下:
​1.index2下一个位置不为*,那么返回false
​2.index2下一个位置为*,那么index2当前位置的字符出现0次。

public class Solution {
    public boolean match(char[] str, char[] pattern)
    {
        return mm(str,pattern,0,0);
    }
    public boolean mm(char[]str, char[] pattern, int index1, int index2 ){
​ // 字符串和模式串均到末尾
        if(index1 == str.length && index2 == pattern.length)
            return true;
​ // 模式串到末尾,字符串没有到末尾
        if(index1!=str.length && index2 == pattern.length)
            return false;
        // 下一个字符不为*
        if(index2 + 1 < pattern.length && pattern[index2 + 1] != '*' || index2 + 1 == pattern.length){
            if(index1<str.length && (str[index1] == pattern[index2] || pattern[index2] == '.'))
                return mm(str, pattern, index1 + 1 , index2 + 1);
            else //字符串到达末尾或者当前字符不匹配
                return false;
        }
​ // 下一个字符为*
        else{
                if(index1 < str.length && (str[index1] == pattern[index2] || pattern[index2] == '.'))
                    return mm(str, pattern, index1, index2+2) || mm(str, pattern, index1 +1 ,index2);
                else //字符串达到末尾或者当前字符不匹配
                    return mm(str, pattern, index1, index2+2);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Lollipop66/article/details/81062047