/
InterLeaving_String.cpp
57 lines (44 loc) · 1.33 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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if (s1.length() + s2.length() != s3.length()) {
return false;
}
int n = s1.size();
int m = s2.size();
vector<vector<int>> f(n+1, vector<int>(m+1,0));
f[0][0] = true;
for (int i = 1; i <= n; i++) {
if(s3[i - 1] == s1[i - 1] && f[i - 1][0])
f[i][0] = true;
}
for (int j = 1; j <= m; j++) {
if(s3[j - 1] == s2[j - 1] && f[0][j - 1])
f[0][j] = true;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if((s3[i + j - 1] == s1[i - 1] && f[i - 1][j])
|| (s3[i + j - 1] == s2[j - 1] && f[i][j - 1]))
f[i][j] = true;
}
}
return f[n][m];
}
};
int main() {
Solution mySol;
string s1("aa");
string s2("ab");
string s3("abaa");
bool is = mySol.isInterleave(s1, s2, s3);
if(is)
cout << s1 << " and " << s2 << " Yes!" << endl;
else
cout << s1 << " and " << s2 << " No!" << endl;
return 0;
}