正则表达式匹配
#include <bits/stdc++.h> using namespace std; //正则匹配 class Solution{ public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @param pattern string字符串 * @return bool布尔型 */ bool match(string str, string pattern) { string s = str; string p = pattern; int n = s.size(),m = p.size(); vector<vector<int>> dp(n+1,vector<int>(m+1,0)); dp[0][0] = 1; for (int i = 1; i < m+1; ++i) { if(p[i-1] =='*') dp[0][i] = dp[0][i-2]; } for (int i = 1; i < n+1 ; ++i) { for (int j = 1; j <m+1 ; ++j) { //case1,直接匹配 if(s[i-1] == p[j-1] || p[j-1] =='.') dp[i][j] = dp[i-1][j-1]; //case2,因为*,分类讨论, else if(p[j-1] =='*'){ //匹配0次或者匹配1或者匹配2次;枚举 if(s[i-1] == p[j-2] || p[j-2] == '.'){ dp[i][j] = dp[i][j-2] || dp[i-1][j-2] ||dp[i-1][j]; } else if(s[i-1] != p[j-2]){ dp[i][j] = dp[i][j-2]; } } } } return dp[n][m]; } };