Skip to content

Commit 8ec6bf4

Browse files
committed
Added memo JS solution for problem 97
1 parent 2978fca commit 8ec6bf4

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

javascript/97-Interleaving-String.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @param {string} s1
3+
* @param {string} s2
4+
* @param {string} s3
5+
* @return {boolean}
6+
*/
7+
function isInterleave(s1, s2, s3) {
8+
9+
const l1 = s1.length;
10+
const l2 = s2.length;
11+
const l3 = s3.length;
12+
13+
if (l1 + l2 !== l3) {
14+
return false;
15+
}
16+
if (!s1 || !s2 || !s3) {
17+
return (!s1 && !s2 && !s3) || (
18+
s1
19+
? s1 === s3
20+
: s2 === s3
21+
);
22+
}
23+
24+
const seen = new Array(l1 + 1).fill()
25+
.map(() => new Array(l2 + 1));
26+
return checkStrings();
27+
28+
/**
29+
* @param {number=} i = `0`
30+
* @param {number=} j = `0`
31+
* @param {number=} k = `0`
32+
* @return {boolean}
33+
*/
34+
function checkStrings(i = 0, j = 0, k = 0) {
35+
return k === l3 || (
36+
seen[i][j] !== undefined
37+
? seen[i][j]
38+
: seen[i][j] = (
39+
i < l1
40+
&& s1[i] === s3[k]
41+
&& checkStrings(i + 1, j, k + 1)
42+
) || (
43+
j < l2
44+
&& s2[j] === s3[k]
45+
&& checkStrings(i, j + 1, k + 1)
46+
)
47+
);
48+
}
49+
}

0 commit comments

Comments
 (0)