leetcode-regular-expression-match

题目大意

  https://leetcode.com/problems/regular-expression-matching/

  跟这个题类似https://leetcode.com/problems/wildcard-matching/,只是匹配规则变化

题目分析

  记忆化搜索,详细解释可以看注释

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
public class Solution {
private char[][] dp;
private char search(String s, int si, String p, int pi) {
int lenS = s.length();
int lenP = p.length();
if (si == lenS && pi == lenP) {
return dp[si][pi] = 1;
}
if (dp[si][pi] > 0) {
return dp[si][pi];
}
char a = 0;
if (si == lenS) {
if (p.charAt(pi) == '*') {
return dp[si][pi] = search(s, si, p, pi + 2);
} else {
// 一定匹配不上
return dp[si][pi] = 2;
}
} else {
a = s.charAt(si);
}
char b = 0;
if (pi == lenP) {
// 一定匹配不上
return dp[si][pi] = 2;
} else {
b = p.charAt(pi);
}
if (b != '*' && b != '.') { // b不是*或者i
if (a != b) {
return dp[si][pi] = 2;
}
return dp[si][pi] = search(s, si + 1, p, pi + 1);
}
if (b == '*') {
if (search(s, si, p, pi + 2) == 1) { //出现星号,先尝试匹配空
return dp[si][pi] = 1;
}
for (int loc = si; loc < lenS; loc++) { //再尝试匹配1-n个
if (s.charAt(loc) != p.charAt(pi + 1) && p.charAt(pi + 1) != '.') { // 注意.*情况
break;
}
if (search(s, loc + 1, p, pi + 2) == 1) {
return dp[si][pi] = 1;
}
}
return dp[si][pi] = 2;
}
if (b == '.') {
return dp[si][pi] = search(s, si + 1, p, pi + 1);
}
return dp[si][pi] = 2;
}
public boolean isMatch(String s, String p) {
if (s == null || p == null) {
return false;
}
s = new StringBuilder(s).reverse().toString();
p = new StringBuilder(p).reverse().toString();
int lenS = s.length();
int lenP = p.length();
dp = new char[lenS + 1][lenP + 1];
for (int i = 0; i <= lenS; i++) {
for (int j = 0; j <= lenP; j++) {
dp[i][j] = 0;
}
}
return search(s, 0, p, 0) == 1 ? true : false;
}
}