forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWildcard matching leetcode solution
61 lines (52 loc) · 1.57 KB
/
Wildcard matching leetcode solution
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//link: https://leetcode.com/problems/wildcard-matching/description/
bool solve(int i, int j, string s1, string s2,vector<vector<int>>& dp){
//base case
if(i<0 && j<0) return true;
if(i>=0 && j<0) return false;
if(i<0 && j>=0){
for(int k =j;k>=0;k--){
if(s2[k]!='*') return false;
}
return true;
}
if(dp[i][j]!=-1) return dp[i][j];
if(s1[i] == s2[j] || s2[j] == '?'){
return dp[i][j] = solve(i-1,j-1,s1,s2,dp);
}
if(s2[j] == '*' ){
return dp[i][j] = solve(i,j-1,s1,s2,dp) | solve(i-1,j,s1,s2,dp);
}
return dp[i][j] = false;
}
bool isMatch(string s, string p) {
int n = s.length();
int m = p.length();
vector<vector<bool>> dp(n+1,vector<bool>(m+1,-1));
dp[0][0] = true;
for(int i=0;i<=n;i++){
dp[i][0] = false;
}
for(int i=0;i<=m;i++){
bool is = true;
for(int j=0;j<i;j++){
if(p[j]!='*'){
is = false;
}
}
dp[0][i] = is;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(s[i-1]==p[j-1] || p[j-1]=='?'){
dp[i][j] = dp[i-1][j-1];
}
else if(p[j-1]=='*'){
dp[i][j] = dp[i][j-1] | dp[i-1][j];
}
else{
dp[i][j] = false;
}
}
}
return dp[n][m];
}