author: Blankj blog : http://blankj.com time : 2017/10/13 desc :
| 9 | * </pre> |
| 10 | */ |
| 11 | public class Solution { |
| 12 | // public boolean isMatch(String s, String p) { |
| 13 | // if (p.isEmpty()) return s.isEmpty(); |
| 14 | // if (p.length() == 1) { |
| 15 | // return s.length() == 1 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'); |
| 16 | // } |
| 17 | // if (p.charAt(1) != '*') { |
| 18 | // if (s.isEmpty()) return false; |
| 19 | // return (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') |
| 20 | // && isMatch(s.substring(1), p.substring(1)); |
| 21 | // } |
| 22 | // // match 1 or more preceding element |
| 23 | // while (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')) { |
| 24 | // if (isMatch(s, p.substring(2))) return true; |
| 25 | // s = s.substring(1); |
| 26 | // } |
| 27 | // // match 0 preceding element |
| 28 | // return isMatch(s, p.substring(2)); |
| 29 | // } |
| 30 | // |
| 31 | // public boolean isMatch(String s, String p) { |
| 32 | // if (p.isEmpty()) return s.isEmpty(); |
| 33 | // if (p.length() > 1 && p.charAt(1) == '*') { |
| 34 | // return isMatch(s, p.substring(2)) |
| 35 | // || (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') |
| 36 | // && isMatch(s.substring(1), p)); |
| 37 | // } |
| 38 | // return !s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') |
| 39 | // && isMatch(s.substring(1), p.substring(1)); |
| 40 | // } |
| 41 | |
| 42 | public boolean isMatch(String s, String p) { |
| 43 | if (p.length() == 0) return s.length() == 0; |
| 44 | int sL = s.length(), pL = p.length(); |
| 45 | boolean[][] dp = new boolean[sL + 1][pL + 1]; |
| 46 | char[] sc = s.toCharArray(), pc = p.toCharArray(); |
| 47 | dp[0][0] = true; |
| 48 | for (int i = 2; i <= pL; ++i) { |
| 49 | if (pc[i - 1] == '*' && dp[0][i - 2]) { |
| 50 | dp[0][i] = true; |
| 51 | } |
| 52 | } |
| 53 | for (int i = 1; i <= sL; ++i) { |
| 54 | for (int j = 1; j <= pL; ++j) { |
| 55 | if (pc[j - 1] == '.' || pc[j - 1] == sc[i - 1]) { |
| 56 | dp[i][j] = dp[i - 1][j - 1]; |
| 57 | } |
| 58 | if (pc[j - 1] == '*') { |
| 59 | if (pc[j - 2] == sc[i - 1] || pc[j - 2] == '.') { |
| 60 | dp[i][j] = dp[i - 1][j] || dp[i][j - 2]; |
| 61 | } else { |
| 62 | dp[i][j] = dp[i][j - 2]; |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | return dp[sL][pL]; |
| 68 | } |
nothing calls this directly
no outgoing calls
no test coverage detected