forked from sanyathisside/Hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RegularExpressionMatching.cpp
35 lines (33 loc) · 1.19 KB
/
RegularExpressionMatching.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 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).
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.length(), n = p.length();
if(n>0 && p[0]=='*')
return false;
vector<vector<bool>> dp(m+1,vector<bool>(n+1,false));
dp[0][0] = true;
for(int i=1; i<=n; i++)
if(p[i-1] == '*' && dp[0][i-2] == true)
dp[0][i] = true;
for(int i=1; i<=m; i++)
dp[i][0] = false;
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] == '*') {
if(p[j-2] == s[i-1] || 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];
}
};