Java LeetCode 10. Regular expression matching

Give you a string s and a character rule p, please come and implement a regular expression matching

that supports'.' and ' '. '.' matches any single character ' ' matches zero or more of the preceding element. The
so-called match is to cover the entire string s, not part of the string.
Example 1:
Input: s = "aa" p = "a"
Output: false
Explanation: "a" cannot match the entire string of "aa".
Example 2:
Input: s = "aa" p = "a
"
Output: true
Explanation: Because'*' means that it can match zero or more of the previous element, where the previous element is'a'. Therefore, the string "aa" can be regarded as'a' repeated once.
*

Use recursion to compare two strings at each level.
There are two situations for each comparison.

In the first case, there is no * sign. In this case, if the two characters are the same or there is a'.' symbol, you can directly return true

In the second case, the next character is the'*' sign, then the symbol can indicate replacement of 0 or an infinite number. If there are 0, the relationship between the next two of right and Left will be judged, and if there are an infinite number, then it will be judged. compare left+1 with current right

class Solution {
    
    
    public boolean isMatch(String s, String p) {
    
    
        return iss(s,0,p,0);
    }
    public boolean iss(String s,int left,String p,int right){
    
    
        if(p.length()==right){
    
    
            return left==s.length();
        }

        boolean isMatch = left<s.length()&&(s.charAt(left)==p.charAt(right)||p.charAt(right)=='.');

        if(right<=p.length()-2&&p.charAt(right+1)=='*'){
    
    
            return iss(s,left,p,right+2)||(isMatch&&iss(s,left+1,p,right));
        }

        return isMatch&&iss(s,left+1,p,right+1);
    }
}

Guess you like

Origin blog.csdn.net/sakura_wmh/article/details/113100513