leetcode-10

Give you a character string s and a law p, invite you to implement a support '' and '*' in the regular expression matching.

'.' Matches any single character
'*' matches zero or more of the preceding element that a
so-called matching, to cover the entire string s, and not part of the string.

Description:

s may be empty, and only lowercase letters az from the.
p may be empty and contain only lowercase letters from az, and characters. and *.
Example 1:

Input:
S = "AA"
P = "A"
Output: false
interpretation: "a" can not match the entire string "aa".
Example 2:

Input:
S = "AA"
P = "A *"
Output: true
explanation: because the '*' matches zero or representatives of the foregoing that a plurality of elements, this is in front of the element 'a'. Thus, the string "aa" may be regarded as 'a' is repeated once.
Example 3:

Input:
S = "ab &"
P = "*."
Output: true
explained: ". *" Denotes zero or more matches ( '*') of any character ( '.').
Example 4:

Input:
S = "AAB"
P = "C * A * B"
Output: true
explanation: because the '*' means zero or more, where 'c' is 0, 'a' is repeated once. So it can match the string "aab".
Example 5:

Input:
S = "Mississippi"
P = "MIS * IS * P *."
Output: false

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/regular-expression-matching
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

class Solution {
    public boolean isMatch(String text, String pattern) {
        if (pattern.isEmpty()) return text.isEmpty();
        boolean first_match = (!text.isEmpty() &&
                (pattern.charAt(0) == text.charAt(0) || pattern.charAt(0) == '.'));

        if (pattern.length() >= 2 && pattern.charAt(1) == '*'){
            // 这里主要考虑aa*aa这种pattern
            return (isMatch(text, pattern.substring(2)) ||
                    (first_match && isMatch(text.substring(1), pattern)));
        } else {
            return first_match && isMatch(text.substring(1), pattern.substring(1));
        }
    }
}

This question some difficulty, I was wondering for a while, no harvest, this partial solution logic, no thinking algorithm.

Guess you like

Origin www.cnblogs.com/CherryTab/p/12040743.html