File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ //find whether String C is formed by interleaving String A and String B
2
+
3
+
4
+ #include <bits/stdc++.h>
5
+ using namespace std;
6
+ string s1,s2,s3;
7
+ int dp[102][102][102];//used to store each state
8
+ bool rec(int i,int j,int k)
9
+ {
10
+ if(dp[i][j][k]!=-1)
11
+ return dp[i][j][k];
12
+ if(i==s1.length()&&j==s2.length()&&k<s3.length()) //base case
13
+ return dp[i][j][k]=0;
14
+
15
+ if(i==s1.length()&&j==s2.length()&&k==s3.length()) //base case
16
+ return dp[i][j][k]=1;
17
+ int ans=0;
18
+ if((i<s1.length())&&s1[i]==s3[k]) //visiting other states
19
+ ans=ans|rec(i+1,j,k+1);
20
+ if(j<s2.length()&&s2[j]==s3[k])
21
+ ans|=rec(i,j+1,k+1);
22
+
23
+ if(i==s1.length()&&s2[j]!=s3[k])
24
+ return 0;
25
+ if(j==s2.length()&&s1[i]!=s3[k])
26
+ return 0;
27
+ if(i<s1.length()&&j<s2.length()&&s1[i]!=s3[k]&&s2[j]!=s3[k])
28
+ return 0;
29
+
30
+ return dp[i][j][k]=ans;
31
+
32
+ }
33
+
34
+ int isInterleave(string A, string B, string C) {
35
+
36
+ memset(dp,-1,sizeof(dp));
37
+ s1=A;
38
+ s2=B;
39
+ s3=C;
40
+ return rec(0,0,0);
41
+
42
+ }
43
+
44
+ int main()
45
+ {
46
+
47
+ string a,b,c;
48
+ cin >> a >> b >> c;
49
+
50
+ if(isInterleave(a,b,c))
51
+ {
52
+ cout << "String C is formed by interleaving String A and String B" << endl;
53
+
54
+ }
55
+ else
56
+ {
57
+ cout << "String C cannot be formed by interleaving String A and String B" << endl;
58
+ }
59
+ }
60
+ //Time complexity: O(N3)
61
+ //Space complexity: O(N3)
62
+
63
+
You can’t perform that action at this time.
0 commit comments