▶ 问题:正则表达式匹配,要求支持 "."(任意单个字符)和 "*"(重复至少0次)。
● 命 P [ i ] [ j ] == true 若模式 p [0...j) 匹配 s [0..i);P [ i ] [ j ] == false 若不匹配,方程:
P[i][j] = P[i - 1][j - 1] // p [ j - 1] != '*' && (s [ i - 1] == p [ j - 1] || p [ j - 1] == '.') P[i][j] = P[i][j - 2] // p [ j - 1] == '*' 且认为 p [ j - 1] 重复了零次 P[i][j] = P[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.') // p [ j - 1] == '*' 且认为模式 p [ j - 1] 重复了至少一次
● 大佬的动态规划法代码,9 ms
1 //static string s = []() {std::ios::sync_with_stdio(false); cin.tie(NULL); return ""; }();// 加了之后变成 3 ms 2 3 class Solution 4 { 5 public: 6 bool isMatch(string s, string p) 7 { 8 int m = s.length(), n = p.length(); 9 vector<vector<bool> > dp(m + 1, vector<bool>(n + 1, false)); 10 dp[0][0] = true; 11 for (int i = 0; i <= m; i++) 12 { 13 for (int j = 1; j <= n; j++) 14 { 15 if (p[j - 1] == '*') 16 dp[i][j] = dp[i][j - 2] || (i > 0 && (s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]); 17 else 18 dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.'); 19 } 20 } 21 return dp[m][n]; 22 } 23 };