File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ //Regex Matching with support for '?' and '*' for Strings A and Strings B
2
+ // 1) �?� : Matches any single character.
3
+ // 2) �*� : Matches any sequence of characters (including the empty sequence)
4
+
5
+
6
+ #include<bits/stdc++.h>
7
+ using namespace std;
8
+
9
+ string s1,s2;
10
+
11
+
12
+ int dp[10000][200];// to store value of each state
13
+
14
+ bool rec(int i,int j)
15
+ {
16
+ bool ans=false;
17
+ if(dp[i][j]!=-1)
18
+ return dp[i][j];
19
+ if(i==s1.length()&&j==s2.length()) // edge case
20
+ return true;
21
+ if(i>s1.length()||j>=s2.length())
22
+ return false;
23
+
24
+ // Now visiting all possible states
25
+ if(s2[j]=='?')
26
+ {
27
+ ans=ans|rec(i+1,j+1);
28
+ }
29
+ else if(s2[j]=='*')
30
+ {
31
+ ans=ans|rec(i+1,j);
32
+ ans=ans|rec(i+1,j+1);
33
+ ans=ans|rec(i,j+1);
34
+ }
35
+ else if(s1[i]==s2[j])
36
+ {
37
+ ans=ans|rec(i+1,j+1);
38
+
39
+ }
40
+ return dp[i][j]=ans;
41
+ }
42
+
43
+ int isMatch(string A,string B)
44
+ {
45
+ s1=A;
46
+ s2=B;
47
+ memset(dp,-1,sizeof(dp));
48
+ return rec(0,0);
49
+
50
+
51
+ }
52
+
53
+ int main()
54
+ {
55
+ string a,b;
56
+ cout << "Enter first String " << endl;
57
+ cin >> a;
58
+
59
+ cout << "Enter second String " << endl;
60
+ cin >> b;
61
+
62
+ if(isMatch(a,b))
63
+ cout << "Both String Match" << endl;
64
+ else
65
+ cout << "Both String does not Match" << endl;
66
+
67
+
68
+ }
69
+ // Time Complexity : O(len(a)*len(b)) where len(x) is length of string x
70
+ // Space Complexity : O(len(a)*len(b)) where len(x) is length of string x
71
+
You can’t perform that action at this time.
0 commit comments