Skip to content

Commit b30fe45

Browse files
Merge pull request codemistic#458 from Ayush-k-Shukla/patch-2
Create Wildcard matching leetcode solution
2 parents 99cdc93 + baf9f3c commit b30fe45

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
2+
3+
//link: https://leetcode.com/problems/wildcard-matching/description/
4+
5+
6+
bool solve(int i, int j, string s1, string s2,vector<vector<int>>& dp){
7+
//base case
8+
if(i<0 && j<0) return true;
9+
if(i>=0 && j<0) return false;
10+
if(i<0 && j>=0){
11+
for(int k =j;k>=0;k--){
12+
if(s2[k]!='*') return false;
13+
}
14+
return true;
15+
}
16+
17+
if(dp[i][j]!=-1) return dp[i][j];
18+
if(s1[i] == s2[j] || s2[j] == '?'){
19+
return dp[i][j] = solve(i-1,j-1,s1,s2,dp);
20+
}
21+
22+
if(s2[j] == '*' ){
23+
return dp[i][j] = solve(i,j-1,s1,s2,dp) | solve(i-1,j,s1,s2,dp);
24+
}
25+
26+
return dp[i][j] = false;
27+
}
28+
bool isMatch(string s, string p) {
29+
int n = s.length();
30+
int m = p.length();
31+
vector<vector<bool>> dp(n+1,vector<bool>(m+1,-1));
32+
dp[0][0] = true;
33+
for(int i=0;i<=n;i++){
34+
dp[i][0] = false;
35+
}
36+
for(int i=0;i<=m;i++){
37+
bool is = true;
38+
for(int j=0;j<i;j++){
39+
if(p[j]!='*'){
40+
is = false;
41+
}
42+
}
43+
dp[0][i] = is;
44+
}
45+
for(int i=1;i<=n;i++){
46+
for(int j=1;j<=m;j++){
47+
if(s[i-1]==p[j-1] || p[j-1]=='?'){
48+
dp[i][j] = dp[i-1][j-1];
49+
}
50+
else if(p[j-1]=='*'){
51+
dp[i][j] = dp[i][j-1] | dp[i-1][j];
52+
}
53+
else{
54+
dp[i][j] = false;
55+
}
56+
}
57+
}
58+
59+
60+
return dp[n][m];
61+
}

0 commit comments

Comments
 (0)