LeetCode刷題記126-44. 萬用字元匹配

鹹蛋黃麥芽糖小餅乾發表於2020-12-10

LeetCode刷題記126

44. 萬用字元匹配

題目
在這裡插入圖片描述

class Solution {
    public boolean isMatch(String s, String p) {
        if (s.length() == 0) {
            if (p.length() == 0) return true;
            for (int i = 0; i < p.length(); i ++) {
                if (p.charAt(i) != '*') return false;
            }
            return true;
        } 
        if (p.length() == 0) {
            return false;
        }
        boolean[][] dp = new boolean[s.length() + 1][p.length() + 1];
        dp[0][0] = true;
        for (int j = 0; j < p.length(); j ++) { 
            if (p.charAt(j) != '*') break;
            dp[0][j + 1] = true;
        }
        for (int i = 0; i < s.length(); i ++) {
            char a = s.charAt(i);
            for (int j = 0; j < p.length(); j ++) {
                char b = p.charAt(j);
                if (a == b || b == '?') {
                    dp[i + 1][j + 1] |= dp[i][j];
                } else {
                    if (b == '*') {
                        dp[i + 1][j + 1] |= dp[i + 1][j];
                        dp[i + 1][j + 1] |= dp[i][j + 1];
                    } 
                }
                // System.out.println("i " + i + "   j "+ j +"  " + dp[i+1][j+1]);
            }
        }
        return dp[s.length()][p.length()];
    }
}

// ""
// "***"
//True

2/3
126/150

相關文章