leetcode10. regular expression matching a string does not explain difficult issues dp

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

dp formula circumstances they want, I do not want to write

I posted a Web site, there are some solution to a problem, but I did not see.

class Solution {
    public boolean isMatch(String s,String p){
        if (s == null || p == null)return false;
        int sLen=s.length();
        int pLen=p.length();
        boolean[][] dp = new boolean[sLen + 1][pLen + 1];
        dp[0][0] = true;//dp[i][j] 表示 s 的前 i 个是否能被 p 的前 j 个匹配
        for (int i = 0; i < pLen; i++) {
            dp[0][i + 1] = p.charAt(i) == '*' && dp[0][i - 1];
        }
        for (int i = 0; i < sLen; i++) {
            for (int j = 0; j < pLen; j++) {
                //单个字符可以匹配
                if (p.charAt(j) == '.' || p.charAt(j) == s.charAt(i)) dp[i + 1][j + 1] = dp[i][j];
                //多个字符
                if (p.charAt(j) == '*') {
                    dp[i+1][j+1]=dp[i+1][j-1] || //*代表0个
                    (dp[i+1][j] && (s.charAt(i)==p.charAt(j-1) || p.charAt(j-1)=='.')) || //*代表1个
                    (dp[i][j+1] && (s.charAt(i)==p.charAt(j-1) || p.charAt(j-1)=='.')); //代表多个
                    }
                }
            }
            return dp[sLen][pLen];
        }
}

 

Published 594 original articles · won praise 10000 + · views 1.39 million +

Guess you like

Origin blog.csdn.net/hebtu666/article/details/104403643