Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created Regular_Expression_Matching.cpp #731

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions Dynamic_Programming/Regular_Expression_Matching.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
//Given a string s and a pattern p, implement regular expression matching with support for '.' (matches any single character) and '*' (zero or more of the preceding element).
//Example:

//Input: s = "mississippi", p = "mis*is*p*."
//Output: false

#include <iostream>
#include <vector>

using namespace std;

bool isMatch(string s, string p) {
int m = s.size();
int n = p.size();
vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
dp[0][0] = true;

// Fill the first row
for (int j = 1; j <= n; ++j) {
if (p[j - 1] == '*') {
dp[0][j] = dp[0][j - 2];
}
}

// Fill the dp array using dynamic programming
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (p[j - 1] == s[i - 1] || p[j - 1] == '.') {
dp[i][j] = dp[i - 1][j - 1];
} else if (p[j - 1] == '*') {
dp[i][j] = dp[i][j - 2] || (dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'));
}
}
}

return dp[m][n];
}

int main() {
string s = "mississippi";
string p = "mis*is*p*.";
bool result = isMatch(s, p);
cout << "Matching result: " << (result ? "true" : "false") << endl;
return 0;
}