File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
C++/Algorithms/Dynamic-Programming Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 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.
You can’t perform that action at this time.
0 commit comments