-
Notifications
You must be signed in to change notification settings - Fork 342
/
Interleaving_string.cpp
73 lines (59 loc) · 1.7 KB
/
Interleaving_string.cpp
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <string.h>
using namespace std;
bool isInterleaved(
char* A, char* B, char* C)
{
int M = strlen(A), N = strlen(B);
bool IL[M + 1][N + 1];
memset(IL, 0, sizeof(IL));
if ((M + N) != strlen(C))
return false;
for (int i = 0; i <= M; ++i) {
for (int j = 0; j <= N; ++j) {
if (i == 0 && j == 0)
IL[i][j] = true;
else if (i == 0) {
if (B[j - 1] == C[j - 1])
IL[i][j] = IL[i][j - 1];
}
else if (j == 0) {
if (A[i - 1] == C[i - 1])
IL[i][j] = IL[i - 1][j];
}
else if (
A[i - 1] == C[i + j - 1]
&& B[j - 1] != C[i + j - 1])
IL[i][j] = IL[i - 1][j];
else if (
A[i - 1] != C[i + j - 1]
&& B[j - 1] == C[i + j - 1])
IL[i][j] = IL[i][j - 1];
else if (
A[i - 1] == C[i + j - 1]
&& B[j - 1] == C[i + j - 1])
IL[i][j]
= (IL[i - 1][j]
|| IL[i][j - 1]);
}
}
return IL[M][N];
}
void test(char* A, char* B, char* C)
{
if (isInterleaved(A, B, C))
cout << C << " is interleaved of "
<< A << " and " << B << endl;
else
cout << C << " is not interleaved of "
<< A << " and " << B << endl;
}
int main()
{
test("XXY", "XXZ", "XXZXXXY");
test("XY", "WZ", "WZXY");
test("XY", "X", "XXY");
test("YX", "X", "XXY");
test("XXY", "XXZ", "XXXXZY");
return 0;
}