Skip to content

Commit f4e45c6

Browse files
committed
Regular Expression Match
1 parent d302eaa commit f4e45c6

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
10+
int dp[10000][200];// to store value of each state
11+
string s1,s2;
12+
13+
bool rec(int i,int j)
14+
{
15+
bool ans=false;
16+
if(dp[i][j]!=-1)
17+
return dp[i][j];
18+
if(i==s1.length()&&j==s2.length()) // edge case
19+
return true;
20+
if(i>s1.length()||j>=s2.length())
21+
return false;
22+
23+
// Now visiting all possible states
24+
if(s2[j]=='?')
25+
{
26+
ans=ans|rec(i+1,j+1);
27+
}
28+
else if(s2[j]=='*')
29+
{
30+
ans=ans|rec(i+1,j);
31+
ans=ans|rec(i+1,j+1);
32+
ans=ans|rec(i,j+1);
33+
}
34+
else if(s1[i]==s2[j])
35+
{
36+
ans=ans|rec(i+1,j+1);
37+
38+
}
39+
return dp[i][j]=ans;
40+
}
41+
42+
int isMatch(string A,string B)
43+
{
44+
s1=A;
45+
s2=B;
46+
memset(dp,-1,sizeof(dp));
47+
return rec(0,0);
48+
49+
50+
}
51+
52+
int main()
53+
{
54+
string a,b;
55+
cout << "Enter first String " << endl;
56+
cin >> a;
57+
58+
cout << "Enter second String " << endl;
59+
cin >> b;
60+
61+
if(isMatch(a,b))
62+
cout << "Both String Match" << endl;
63+
else
64+
cout << "Both String does not Match" << endl;
65+
66+
67+
}
68+
// Time Complexity : O(len(a)*len(b)) where len(x) is length of string x
69+
// Space Complexity : O(len(a)*len(b)) where len(x) is length of string x
70+

0 commit comments

Comments
 (0)