DP #44 Wildcard Matching

Link: https://leetcode.com/problems/wildcard-matching

class Solution {
    public boolean isMatch(String s, String p) {
        // int n = s.length(), m = p.length();
        // int[][] dp = new int[n][m];
        // for (int[] r : dp)
        // Arrays.fill(r, -1);
        // return recur(n - 1, m - 1, s, p, dp);
        return tab(s, p);
    }

    boolean isAllStars(int i, String p) {
        for (int k = i; k > 0; k--) {
            if (p.charAt(k - 1) != '*')
                return false;
        }
        return true;
    }

    boolean tab(String s, String p) {
        int n = s.length(), m = p.length();
        boolean[][] dp = new boolean[n + 1][m + 1];
        dp[0][0] = true;
        for (int i = 1; i <= m; i++)
            dp[0][i] = isAllStars(i, p);

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '?')
                    dp[i][j] = dp[i - 1][j - 1];
                else {
                    // * case
                    if (p.charAt(j - 1) == '*') {
                        boolean nm = dp[i][j - 1];
                        boolean ym = dp[i - 1][j];
                        dp[i][j] = nm || ym;
                    } else
                        dp[i][j] = false;
                }
            }
        }
        return dp[n][m];
    }

    boolean recur(int i, int j, String s, String p, int[][] dp) {
        if (i < 0 && j < 0)
            return true;
        if (i >= 0 && j < 0)
            return false;
        // * case
        if (i < 0 && j >= 0)
            return isAllStars(j, p);

        if (dp[i][j] != -1)
            return (dp[i][j] == 1) ? true : false;
        if (s.charAt(i) == p.charAt(j) || p.charAt(j) == '?') {
            boolean res = recur(i - 1, j - 1, s, p, dp);
            dp[i][j] = (res) ? 1 : 0;
            return res;
        } else {
            // * case
            if (p.charAt(j) == '*') {
                boolean nm = recur(i, j - 1, s, p, dp); // no * match
                boolean ym = recur(i - 1, j, s, p, dp); // yes * one/more match
                boolean res = nm || ym;
                dp[i][j] = (res) ? 1 : 0;
                return res;
            }
        }
        dp[i][j] = 0;
        return false;
    }
}