Given an input string (s
) and a pattern (p
), implement regular expression matching with support for '.'
and '*'
where:
'.'
Matches any single character.'*'
Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Example:
Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Approach:
C++
#include <bits/stdc++.h>using namespace std;bool isMatch(string a, string b){int n = a.size(), m = b.size();vector<vector<bool>> dp(n + 1, vector<bool>(m + 1, 0));for (int i = 0; i <= n; i++){for (int j = 0; j <= m; j++){if (i == 0){dp[i][j] = (j == 0);if (j && b[j - 1] == '*')dp[i][j] = dp[i][j - 2];}else{//one character matchif (j && b[j - 1] == '.'){dp[i][j] = dp[i - 1][j - 1];}//if 0 or more character matchelse if (j && b[j - 1] == '*'){//if 0 or more character matchif (b[j - 2] == '.'){dp[i][j] = (dp[i - 1][j] ||dp[i][j - 2]);}else{if (a[i - 1] == b[j - 2]){dp[i][j] = (dp[i - 1][j] ||dp[i][j - 2]);}else{dp[i][j] = dp[i][j - 2];}}}else if (i && j){dp[i][j] = (a[i - 1] == b[j - 1] &&dp[i - 1][j - 1]);}}}}return dp[n][m];}int main(){string s = "aa", p = "a*";if (isMatch(s, p))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment