1 class Solution {
 2     public boolean isMatch(String s, String p) {
 3 
 4     if (s == null || p == null) {
 5         return false;
 6     }
 7     boolean[][] dp = new boolean[s.length()+1][p.length()+1];
 8     dp[0][0] = true;
 9     for (int i = 0; i < p.length(); i++) {
10         if (p.charAt(i) == '*' && dp[0][i-1]) {
11             dp[0][i+1] = true;
12         }
13     }
14     for (int i = 0 ; i < s.length(); i++) {
15         for (int j = 0; j < p.length(); j++) {
16             if (p.charAt(j) == '.') {
17                 dp[i+1][j+1] = dp[i][j];
18             }
19             if (p.charAt(j) == s.charAt(i)) {
20                 dp[i+1][j+1] = dp[i][j];
21             }
22             if (p.charAt(j) == '*') {
23                 if (p.charAt(j-1) != s.charAt(i) && p.charAt(j-1) != '.') {
24                     dp[i+1][j+1] = dp[i+1][j-1];
25                 } else {
26                     dp[i+1][j+1] = (dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]);
27                 }
28             }
29         }
30     }
31     return dp[s.length()][p.length()];
32 }
33 }

参考:https://leetcode.com/problems/regular-expression-matching/discuss/5651/Easy-DP-Java-Solution-with-detailed-Explanation

补充一个python的实现:

 1 class Solution:
 2     def isMatch(self, s: 'str', p: 'str') -> 'bool':
 3         m,n = len(s),len(p)
 4         #dp[i][j]表示s[:i+1]是否可以匹配p[:j+1]
 5         dp = [[False for _ in range(n+1)]for _ in range(m+1)]
 6         #前提,空白字符可以匹配空白规则
 7         dp[0][0] = True
 8         #如果有*,则*前的字符可以省略
 9         for j in range(1,n+1):
10             if (p[j-1] == '*'):
11                 dp[0][j] = dp[0][j-2]
12 
13         for i in range(1,m+1):
14             for j in range(1,n+1):
15                 if s[i-1] == p[j-1]:#s与p的当前位置上相同
16                     dp[i][j] = dp[i-1][j-1]#当前位置与左上角(同时去掉s和p的当前位置后)匹配性相同
17                 elif p[j-1] == '.':#p当前位置是'.',可以匹配任意1个字符
18                     dp[i][j] = dp[i-1][j-1]#当前位置与左上角(同时去掉s和p的当前位置后)匹配性相同
19                 elif p[j-1] == '*':#p当前位置是'*',可以匹配任意0个、1个或多个字符
20                     if s[i-1] == p[j-2]:#s与p的前一位置上相同
21                         #假设s字符串是ba,p模式串是ba*
22                         #(b->ba*) or (ba->ba) or (ba->b)
23                         #这三种只要有一种是True,就说明可以匹配
24                         dp[i][j] = dp[i-1][j] or dp[i][j-1] or dp[i][j-2]
25                     elif p[j-2] == '.':#再次使用 当前字符匹配性判断1
26                         dp[i][j] = dp[i-1][j] or dp[i][j-1] or dp[i][j-2]
27                     else:
28                         dp[i][j] = dp[i][j-2]
29 
30         return dp[m][n]

 

本题与剑指Offer 19 正则表达式匹配是同一道题。

posted on 2019-03-07 11:51  Sempron2800+  阅读(237)  评论(0编辑  收藏  举报