Created
September 1, 2017 06:53
-
-
Save jianminchen/e24b302cd5a7ce9e2fa9959b36b40742 to your computer and use it in GitHub Desktop.
Leetcode 10 - dynamic programming - study code using Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
class Solution { | |
static boolean isMatch(String text, String pattern) { | |
// your code goes here | |
if (text == null && pattern == null) { | |
return true; | |
} | |
if (text == null || pattern == null) { | |
return false; | |
} | |
if (text.length() == 0 && pattern.length() == 0) { | |
return true; | |
} | |
if (text.length() != 0 && pattern.length() == 0) { //"", "a*" true | |
return false; | |
} | |
if (pattern.charAt(0) == '*') { | |
return false; | |
} | |
int lenT = text.length(); | |
int lenP = pattern.length(); | |
char[] t = text.toCharArray(); | |
char[] p = pattern.toCharArray(); | |
boolean[][] dp = new boolean[lenT + 1][lenP + 1]; | |
dp[0][0] = true; | |
for (int i = 1; i <= lenT; i++) { | |
dp[i][0] = false; | |
} | |
for (int i = 1; i <= lenP; i++) { | |
if (i == 1) { | |
dp[0][i] = false; | |
continue; | |
} | |
dp[0][i] = (p[i - 1] == '*' && dp[0][i - 2]); | |
} | |
for (int i = 1; i <= lenT; i++) { | |
for (int j = 1; j <= lenP; j++) { | |
// t[i - 1] and p[j - 1] | |
if (p[j - 1] == '.') { | |
dp[i][j] = dp[i - 1][j - 1]; | |
} else if (p[j - 1] == '*') { | |
dp[i][j] = dp[i][j - 2] || ((t[i - 1] == p[j - 2] || p[j - 2] == '.')&& dp[i - 1][j]); // ? * 0 , 1 or more than 1, a*, A||B||C, case A, B, C, | |
} else if (p[j - 1] == t[i - 1]) { | |
dp[i][j] = dp[i - 1][j - 1]; | |
} else { | |
dp[i][j] = false; | |
} | |
} | |
} | |
return dp[lenT][lenP]; | |
} | |
public static void main(String[] args) { | |
System.out.println(isMatch("abaa", "a.*a*")); | |
} | |
} | |
// Leetcode 10 hard level algorithm | |
// . stands for any char, . match a - z, match one char | |
// * stands for 0 or 1 or more than 1 times | |
// a* -> "", 0 | |
// a* -> "a", 1 | |
// a* -> aa | |
// a*a -> a, aa, aaa | |
// .* (1) a (2) aa (3) ab | |
// .* != .., a - z | |
// .*: . | .. | ... | |
// dp [i ,j ] means if text[0 .. i] pattern[0 .. j] matches | |
// dp [text.length - 1, pattern.length - 1] would be the answer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment