-
Notifications
You must be signed in to change notification settings - Fork 130
/
Interleaving String.js
102 lines (80 loc) · 2.07 KB
/
Interleaving String.js
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
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.
*/
//dp
/**
* @param {string} s1
* @param {string} s2
* @param {string} s3
* @return {boolean}
*/
var isInterleave = function(s1, s2, s3) {
let dp = [];
const len1 = s1.length;
const len2 = s2.length;
const len3 = s3.length;
if (len1 + len2 !== len3) {
return false;
}
for (let i = 0; i <= len1; i++) {
const arr = new Array(len2 + 1).fill(false);
dp.push(arr);
}
dp[0][0] = true;
for (let i = 1; i <= len1; i++) {
dp[i][0] = s1.charAt(i - 1) === s3.charAt(i - 1);
if (!dp[i][0]) {
break;
}
}
for (let j = 1; j <= len2; j++) {
dp[0][j] = s2.charAt(j - 1) === s3.charAt(j - 1);
if (!dp[0][j]) {
break;
}
}
for (let i = 1; i <= len1; i++) {
for (let j = 1; j <= len2; j++) {
let k = i + j - 1;
dp[i][j] = (dp[i][j - 1] && (s2.charAt(j - 1) === s3.charAt(k))) || (dp[i - 1][j] && (s1.charAt(i - 1) === s3.charAt(k)));
}
}
return dp[len1][len2];
};
// Time Limit Exceeded
/**
* @param {string} s1
* @param {string} s2
* @param {string} s3
* @return {boolean}
*/
var isInterleave = function(s1, s2, s3) {
if (!s1) {
return s2 === s3;
}
if (!s2) {
return s1 === s3;
}
if (s3.length !== s1.length + s2.length) {
return false;
}
const c1 = s1.charAt(0);
const c2 = s2.charAt(0);
const c3 = s3.charAt(0);
if (c1 === c3 && c2 === c3) {
return isInterleave(s1.substr(1), s2, s3.substr(1)) || isInterleave(s1, s2.substr(1), s3.substr(1));
}
if (c1 === c3) {
return isInterleave(s1.substr(1), s2, s3.substr(1));
}
if (c2 === c3) {
return isInterleave(s1, s2.substr(1), s3.substr(1));
}
return false;
};