Short Java DP


  • 0
    M
    	public boolean isMatch(String s, String p) {
    		if (s == null || p == null) return false;
    		int m = s.length(), n = p.length();
    		boolean[][] dp = new boolean[m + 1][n + 1];
    		dp[0][0] = true;
    		for (int i = 0; i <= m; ++i) {
    			for (int j = 1; j <= n; ++j) {
    				if (j < n && p.charAt(j) == '*') continue;
    				if (p.charAt(j - 1) != '*') {
    					dp[i][j] = i > 0 && dp[i - 1][j - 1] && (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1));
    				} else {
    					if (j <= 1) return false; // invalid pattern starting with '*'
    					dp[i][j] = dp[i][j - 2] || i > 0 && dp[i - 1][j] && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1));
    				}
    			}
    		}
    		return dp[m][n];
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.