Skip to content

Commit e17803d

Browse files
authored
Merge pull request div-bargali#261 from nakuljn/main
added a dp problem, wildcard matching
2 parents be2448d + 83eccab commit e17803d

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
//creating a function for wildcard matching
5+
bool isMatch(string s, string p) {
6+
int n = s.size();
7+
int m = p.size();
8+
9+
//declaring a dp table of size n+1 * m+1
10+
vector<vector<int>> dp(n+1, vector<int>(m+1, true));
11+
12+
//initialsing mth column as false
13+
for(int i = n-1; i >= 0; i--){
14+
dp[i][m] = false;
15+
}
16+
17+
18+
for(int j = m-1; j >= 0; j--){
19+
if(p[j] == '*') dp[n][j] = dp[n][j+1] && true;
20+
else dp[n][j] = false;
21+
}
22+
23+
24+
for(int i = n-1; i >= 0; i--){
25+
for(int j = m-1; j >= 0; j--){
26+
27+
//if characters are same we move ahead.
28+
if(s[i] == p[j]) dp[i][j] = dp[i+1][j+1];
29+
30+
//if we encounter a '?' we just move ahead in both strings.
31+
else if(p[j] == '?') dp[i][j] = dp[i+1][j+1];
32+
33+
//if we encounter a '*' in p we use the then match the remaining string of s with p (no change in position in p)
34+
//or we just skip that letter in p.
35+
else if(p[j] == '*') dp[i][j] = dp[i+1][j] || dp[i][j+1];
36+
37+
else dp[i][j] = false;
38+
}
39+
}
40+
41+
return dp[0][0];
42+
43+
}
44+
45+
//driver code
46+
int main(){
47+
string s = "adceb";
48+
string p = "*a*b";
49+
if(isMatch(s, p))
50+
cout<<"Yes the two patterns match"<<endl;
51+
else
52+
cout<<"No the two patterns dont match"<<endl;
53+
}
54+
55+
// the above program will output yes.

0 commit comments

Comments
 (0)