10.regular-expression-matching.java 843 B

1234567891011121314151617181920
  1. class Solution {
  2. public boolean isMatch(String s, String p) {
  3. char[] str = s.toCharArray(), pat = p.toCharArray();
  4. boolean[][] dp = new boolean[str.length + 1][pat.length + 1];
  5. dp[0][0] = true;
  6. // dp[i][0] = false, 0 < i
  7. for (int i = 1; i <= pat.length; i++)
  8. dp[0][i] = 1 < i && pat[i - 1] == '*' && dp[0][i - 2];
  9. for (int i = 1; i <= str.length; i++) {
  10. for (int j = 1; j <= pat.length; j++) {
  11. if (pat[j - 1] == '*') {
  12. dp[i][j] = dp[i][j - 2] || ((pat[j - 2] == '.' || str[i - 1] == pat[j - 2]) && dp[i - 1][j]);
  13. } else {
  14. dp[i][j] = (pat[j - 1] == '.' || str[i - 1] == pat[j - 1]) && dp[i - 1][j - 1];
  15. }
  16. }
  17. }
  18. return dp[str.length][pat.length];
  19. }
  20. }