10. 正则表达式匹配

实现支持.和*的正则表达式匹配.

思路: 动态规划

f[i][j]f[i][j] 表示ss中的前ii 个字母能否与pp 中的前jj 个字母匹配, 按照p[j]p[j]是否为*分为两种情况

存在*时的转移方程可以这样考虑:

  1. 匹配 s 末尾的一个字符,将该字符扔掉,而该组合还可以继续进行匹配;(f[i1][j]f[i-1][j])

  2. 不匹配字符,将该组合扔掉,不再进行匹配。(f[i][j2]f[i][j - 2])

最终的状态转移方程:

f[i][j]={f[i1][j1],p[j] and s[i]=p[j]false,p[j] and s[i]p[j]f[i][j2] or f[i1][j],p[j]= and s[i]=p[j1]f[i][j2],p[j]= and s[i]p[j1]f[i][j] = \begin{cases} f[i - 1][j - 1], & p[j] \neq '*' ~and~ s[i] = p[j] \\ false, & p[j] \neq '*' ~and~ s[i] \neq p[j] \\ f[i][j - 2] ~or~ f[i-1][j], & p[j] = '*' ~and~ s[i] = p[j-1] \\ f[i][j - 2], & p[j] = '*' ~and~ s[i] \neq p[j-1] \end{cases}

代码:

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
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.size();
int n = p.size();

auto matches = [&](int i, int j) {
if (i == 0) {
return false;
}
if (p[j - 1] == '.') {
return true;
}
return s[i - 1] == p[j - 1];
};

vector<vector<int>> f(m + 1, vector<int>(n + 1));
f[0][0] = true;
for (int i = 0; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (p[j - 1] == '*') {
f[i][j] |= f[i][j - 2];
if (matches(i, j - 1)) {
f[i][j] |= f[i - 1][j];
}
}
else {
if (matches(i, j)) {
f[i][j] |= f[i - 1][j - 1];
}
}
}
}
return f[m][n];
}
};