Java arithmetic exercises - regular expression matching

Topic Link

Title Description

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

'.' 匹配任意单个字符
'*' 匹配零个或多个前面的那一个元素

The so-called matching, is 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

输入:
s = "aa"
p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。

Example 2

输入:
s = "aa"
p = "a*"
输出: true
解释: 因为 '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 'a'。因此,字符串 "aa" 可被视为 'a' 重复了一次。

Example 3

输入:
s = "ab"
p = ".*"
输出: true
解释: ".*" 表示可匹配零个或多个('*')任意字符('.')。

Example 4

输入:
s = "aab"
p = "c*a*b"
输出: true
解释: 因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。

Example 5

输入:
s = "mississippi"
p = "mis*is*p*."
输出: false

Solution to a problem (back)

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) == '*'){
        return (isMatch(text, pattern.substring(2)) ||
                (first_match && isMatch(text.substring(1), pattern)));
    } else {
        return first_match && isMatch(text.substring(1), pattern.substring(1));
    }
}

Solution to a problem (dynamic programming)

public boolean isMatch(String text, String pattern) {
    boolean[][] dp = new boolean[text.length() + 1][pattern.length() + 1];
    dp[text.length()][pattern.length()] = true;

    for (int i = text.length(); i >= 0; i--){
        for (int j = pattern.length() - 1; j >= 0; j--){
            boolean first_match = (i < text.length() &&
                                   (pattern.charAt(j) == text.charAt(i) ||
                                    pattern.charAt(j) == '.'));
            if (j + 1 < pattern.length() && pattern.charAt(j+1) == '*'){
                dp[i][j] = dp[i][j+2] || first_match && dp[i+1][j];
            } else {
                dp[i][j] = first_match && dp[i+1][j+1];
            }
        }
    }
    return dp[0][0];
}

Complexity Analysis

Not really understand, power button solution to a problem write, we look at that now.

Notes

For me this chicken dish, this question quite hard. Now only read the official explanations, behind even more over time at practice.

Guess you like

Origin www.cnblogs.com/mxwbq/p/10956779.html