leetcode

 1 class Solution {
 2     public boolean isMatch(String s, String p) {
 3         if (s == null || p == null) {
 4             return false;
 5         }
 6         boolean[][] memo = new boolean[s.length()][p.length()];
 7         boolean[][] visited = new boolean[s.length()][p.length()];
 8         return helper(s, 0, p, 0, memo, visited);
 9     }
10     private boolean helper(String s, int sIndex, String p, int pIndex, boolean[][] memo, boolean[][] visited) {
11         if (pIndex == p.length()) {
12             return s.length() == sIndex;
13         }
14         if (s.length() == sIndex) {
15             return isAllStar(p, pIndex);
16         }
17         if (visited[sIndex][pIndex]) {
18             return memo[sIndex][pIndex];
19         }
20         char pChar = p.charAt(pIndex);
21         char sChar = s.charAt(sIndex);
22         boolean match = false;
23         if (pChar == '*') {
24             if (p.charAt(pIndex - 1) == '.') {
25                 match = helper(s, sIndex + 1, p, pIndex, memo, visited) || helper(s, sIndex, p, pIndex + 1, memo, visited);
26             } else {
27                 // if (sChar == p.charAt(pIndex - 1)) {
28                 //     match = helper(s, sIndex + 1, p, pIndex, memo, visited) || helper(s, sIndex, p, pIndex + 1, memo, visited);
29                 // } else {
30                 //     match = false;
31                 // }
32                 match = (sChar == p.charAt(pIndex - 1) && helper(s, sIndex + 1, p, pIndex, memo, visited)) || helper(s, sIndex, p, pIndex + 1, memo, visited);
33             }
34         } else {
35 //          "aab"
36 //          "c*a*b"
37             if (pChar )
38             match = (pChar == sChar || pChar == '.') && helper(s, sIndex + 1, p, pIndex + 1, memo, visited); 
39         }
40         visited[sIndex][pIndex] = true;
41         memo[sIndex][pIndex] = match;
42         return match;
43     }
44     private boolean isAllStar(String p, int pIndex) {
45         for (int i = pIndex; i < p.length(); i++) {
46             if (p.charAt(pIndex) != '*') {
47                 return false;
48             }
49         }
50         return true;
51     }
52 }
View Code

dp

原文地址:https://www.cnblogs.com/yunyouhua/p/9409276.html