题目描述

https://leetcode.cn/problems/zheng-ze-biao-da-shi-pi-pei-lcof/
image.png

解题思路

https://leetcode.cn/problems/zheng-ze-biao-da-shi-pi-pei-lcof/solution/jian-zhi-offer-19-zheng-ze-biao-da-shi-pi-pei-dong/
image.png

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