|
| 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 isMatchHelper(s, 0, p, 0, memo, visited); |
| 9 | + } |
| 10 | + private boolean charMatch(char sChar, char pChar) { |
| 11 | + return (sChar == pChar || pChar == '?'); |
| 12 | + } |
| 13 | + private boolean allStar(String p, int pIndex) { |
| 14 | + for (int i = pIndex; i < p.length(); i++) { |
| 15 | + if (p.charAt(i) != '*') { |
| 16 | + return false; |
| 17 | + } |
| 18 | + } |
| 19 | + return true; |
| 20 | + } |
| 21 | + private boolean isMatchHelper(String s, int sIndex, |
| 22 | + String p, int pIndex, |
| 23 | + boolean[][] memo, |
| 24 | + boolean[][] visited) { |
| 25 | + if (pIndex == p.length()) { |
| 26 | + return sIndex == s.length(); |
| 27 | + } |
| 28 | + if (sIndex == s.length()) { |
| 29 | + return allStar(p, pIndex); |
| 30 | + } |
| 31 | + if (visited[sIndex][pIndex]) { |
| 32 | + return memo[sIndex][pIndex]; |
| 33 | + } |
| 34 | + |
| 35 | + char sChar = s.charAt(sIndex); |
| 36 | + char pChar = p.charAt(pIndex); |
| 37 | + boolean match; |
| 38 | + |
| 39 | + if (pChar == '*') { |
| 40 | + match = isMatchHelper(s, sIndex, p, pIndex + 1, memo, visited) || |
| 41 | + isMatchHelper(s, sIndex + 1, p, pIndex, memo, visited); |
| 42 | + } else { |
| 43 | + match = charMatch(sChar, pChar) && |
| 44 | + isMatchHelper(s, sIndex + 1, p, pIndex + 1, memo, visited); |
| 45 | + } |
| 46 | + |
| 47 | + visited[sIndex][pIndex] = true; |
| 48 | + memo[sIndex][pIndex] = match; |
| 49 | + return match; |
| 50 | + } |
| 51 | +} |
0 commit comments