Prove safety Offer: regular expression matching (java version)

Title Description

Implement comprises a function to match '' and '*' regular expression. Mode character '.' Represents any one character '*' indicates that the preceding character can appear any number of times (including 0 time). In this problem, the match is a whole pattern matches all characters of the string. For example, the string "aaa" mode and "aa" and "ab * ac * a" match, but the "aa.a" and "ab * a" do not match.

analysis

Two cases: the pattern is a character '*' or as '*':
the next character is not a 1.pattern '*': this situation is relatively simple, direct current character matches. If the match is successful, continue to the next match; if the match fails, direct returns false. Note that "match success", in addition to the case where the same two characters, there is a case that the pattern of the current character '.'
2.pattern next character of '*' is slightly more complicated, because the '* 'I can represent 0 or more. Here these circumstances are taken into account:
A> when the '*' matches zero characters, str constant current character, pattern 2 after the current shift character, skip this '* X';
B> when the '*' matches 1 when a, str current toward a lower symbol, pattern 2 after the current shift character.
c> when the '*' is a plurality of matched, str toward a current character, pattern constant current character.

Recursion

public class Solution {
    public boolean match(char[] str, char[] pattern) {
    if (str == null || pattern == null) {
        return false;
        }
    return ismatch(str, 0, pattern, 0);
    } 
    public boolean ismatch(char[] str,int i,char[] pattern,int j){
        if(j==pattern.length){ //j到了末尾
            return i==str.length; //i必须也到末尾才为true,否则为false
        }
        if(j+1 < pattern.length && pattern[j+1]=='*' ){ // j+1不越界并且为*
            if((i!=str.length && str[i]==pattern[j]) ||( pattern[j]=='.' && i!=str.length)){ // 当前位能匹配上
                return ismatch(str,i,pattern,j+2) || ismatch(str,i+1,pattern,j+2) || ismatch(str,i+1,pattern,j);
            }else{ // 当前位匹配不上
                return ismatch(str,i,pattern,j+2);
            }
        }
        // j+1越界了 或者下一位不是*,那么必须当前位是匹配的
        if((i!=str.length && str[i]==pattern[j] )|| (pattern[j]=='.' && i!=str.length)){
            return ismatch(str,i+1,pattern,j+1);
        }
        return false;
    }
}

Guess you like

Origin blog.csdn.net/qq_43165002/article/details/90476090