lc-44


//Given an input string (s) and a pattern (p), implement wildcard pattern matchi
//ng with support for '?' and '*' where: 
//
// 
// '?' Matches any single character. 
// '*' Matches any sequence of characters (including the empty sequence). 
// 
//
// The matching should cover the entire input string (not partial). 
//
// 
// Example 1: 
//
// 
//Input: s = "aa", p = "a"
//Output: false
//Explanation: "a" does not match the entire string "aa".
// 
//
// Example 2: 
//
// 
//Input: s = "aa", p = "*"
//Output: true
//Explanation: '*' matches any sequence.
// 
//
// Example 3: 
//
// 
//Input: s = "cb", p = "?a"
//Output: false
//Explanation: '?' matches 'c', but the second letter is 'a', which does not mat
//ch 'b'.
// 
//
// 
// Constraints: 
//
// 
// 0 <= s.length, p.length <= 2000 
// s contains only lowercase English letters. 
// p contains only lowercase English letters, '?' or '*'. 
// 
// Related Topics String Dynamic Programming Greedy Recursion 
// 👍 5102 👎 226


//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public boolean isMatch(String s, String p) {
        //dp[sidx][pidx]代表长为sidx的s的子串与长为pidx的p的子串的匹配情况
        boolean[][] dp = new boolean[s.length() + 1][p.length() + 1];
        dp[0][0] = true;
        for(int i = 1; i <= p.length(); i++){
            if(p.charAt(i - 1) != '*'){
                break;
            }
            dp[0][i] = dp[0][i - 1];
        }

        for(int sidx = 1; sidx <= s.length(); ++sidx){
            for(int pidx = 1; pidx <= p.length(); ++pidx){
                //若当前字符匹配或者p串字符为‘?’,dp[sidx][pidx]取决于dp[sidx - 1][pidx - 1]
                if(p.charAt(pidx - 1) == s.charAt(sidx - 1) || p.charAt(pidx - 1) == '?'){
                    dp[sidx][pidx] = dp[sidx - 1][pidx - 1];
                }
                //若当前p串字符为‘*’,dp[sidx][pidx]取决于dp[sidx][pidx - 1](出现0次)或者dp[sidx - 1][pidx](出现多次);
                else if(p.charAt(pidx - 1) == '*'){
                    dp[sidx][pidx] = dp[sidx][pidx - 1] || dp[sidx - 1][pidx];
                }
            }
        }
        return dp[s.length()][p.length()];
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !