-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisInterleave.cpp
More file actions
executable file
·58 lines (50 loc) · 1.31 KB
/
isInterleave.cpp
File metadata and controls
executable file
·58 lines (50 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
*/
#include <algorithm>
#include <vector>
#include <cstring>
#include <iostream>
using namespace std;
bool isIterleave(string s1, string s2, string s3){
int n1 = s1.size();
int n2 = s2.size();
int n3 = s3.size();
if(n1 + n2 != n3) return false;
vector<vector<bool>> D(n1+1, vector<bool>(n2 + 1, false));
D[0][0] = 1;
for(int i = 0; i < n2; ++i){
if(s2[i] != s3[i])
break;
D[0][i+1] = true;
}
for(int i = 0; i < n1; ++i){
if(s1[i] != s3[i])
break;
D[i+1][0] = true;
}
for(int i = 1; i <= n1; ++i)
for(int j = 1; j <= n2; ++j){
if(s1[i-1] == s3[i+j-1] && s3[i+j-1] != s2[j-1])
D[i][j] = D[i-1][j];
else if(s1[i-1] != s3[i+j-1] && s3[i+j-1] == s2[j-1])
D[i][j] = D[i][j-1];
else if(s1[i-1] == s3[i+j-1] && s3[i+j-1] == s2[j-1])
D[i][j] = (D[i][j-1] || D[i-1][j]);
}
return D[n1][n2];
}
int main(int argc, char const *argv[])
{
string s1 = "aabcc";
string s2 = "dbbca";
string s3 = "aadbbcbcac";
cout << isIterleave(s1,s2,s3) << endl;
return 0;
}