https://leetcode.com/problems/regular-expression-matching/description/express
DP:spa
class Solution { public: bool isMatch(string s, string p) { int m = s.length(), n = p.length(); vector<vector<bool>> dp(m+1, vector<bool>(n+1, false)); dp[0][0] = true; for (int j = 1; j < n; j++) { if (p[j] == '*') dp[0][j+1] = dp[0][j-1]; // we should p[j-1]p[j] } for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) { if (s[i-1] == p[j-1] || p[j-1] == '.') dp[i][j] = dp[i-1][j-1]; else if (j-1 > 0 && p[j-1] == '*') { if (s[i-1] == p[j-2] || p[j-2] == '.') dp[i][j] = dp[i][j-2] || dp[i-1][j]; else dp[i][j] = dp[i][j-2]; } } return dp[m][n]; } };
recursioncode
class Solution { public: bool isMatch(string s, string p) { int m = s.length(), n = p.length(); if (n == 0) return m == 0; bool firstMatch = m > 0 && (s[0] == p[0] || p[0] == '.'); if (n > 1 && p[1] == '*') { if (firstMatch && isMatch(s.substr(1), p)) return true; return isMatch(s, p.substr(2)); } return firstMatch && isMatch(s.substr(1), p.substr(1)); } };