Sword refers to Offer-49-regular expression matching

Title description

Please implement a function to match regular expressions including'.' and ' '. The character'.' in the pattern means any character, and ' ' means that the character before it can appear any number of times (including 0 times). In this question, matching means that all characters of the string match the entire pattern. For example, the string "aaa" matches the patterns "aa" and "ab ac a", but does not match neither "aa.a" nor "ab*a"

Idea analysis

The mentality burst. I do it step by step in my own way. But there is a problem. I went to read other people's answers, and the logic was the same as mine, but it passed, so I wrote them one by one. Still wrong. Forget it, we still have to be flexible to solve this problem. Don't be too rigid. Take a look at the dynamic planning of other bigwigs!

Code

链接:https://www.nowcoder.com/questionTerminal/45327ae22b7b413ea21df13ee7d6429c
来源:牛客网

public static boolean match(char[] str, char[] pattern)
    {
    
    
        if(str == null || pattern == null)
            return false;
        return match(str, 0, pattern, 0);
    }
private  boolean match(char[] str, int i, char[] pattern, int j) {
    
    
       if(j == pattern.length)//pattern遍历完了
            return str.length == i;//如果str也完了,返回true,不然false
       //注意数组越界问题,一下情况都保证数组不越界
       if(j < pattern.length - 1 && pattern[j + 1] == '*') {
    
    //下一个是*
           if(str.length != i && //当前匹配
                   (str[i] == pattern[j] || pattern[j] == '.')) //匹配
               return match(str,i,pattern,j + 2)
                       || match(str,i + 1,pattern,j);
           else//当前不匹配
               return match(str,i,pattern,j + 2);
       }
       //下一个不是“*”,当前匹配
       if(str.length != i && (str[i] == pattern[j] || pattern[j] == '.'))
           return match(str,i + 1,pattern,j + 1);
        return false;
    }

I am basically the same as this code, but there are differences in variable naming, but there is a problem. ! ! !

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107501132