Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.

Commit fd56c15

Browse files
committed
Reimplement combine strings, much easier to precompute paths.
1 parent e5299b4 commit fd56c15

File tree

1 file changed

+18
-17
lines changed

1 file changed

+18
-17
lines changed
+18-17
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
1-
var combineTwoStrings = function (str1, str2, str3) {
2-
var pos1 = 0,
3-
pos2 = 0;
4-
5-
if (str1 + str2 === str3) { return true; }
6-
7-
for (var i = 0; i < str3.length; i++) {
8-
if (str3[i] === str1[pos1]) {
9-
pos1++;
10-
}
11-
else if (str3[i] === str2[pos2]) {
12-
pos2++;
13-
}
14-
else if (str3.length - i - 1 < str1.length - pos1 + str2.length - pos2) {
15-
return false;
16-
}
1+
var combineTwoStrings = function (str1, str2, combined) {
2+
// Generate all the posible paths between `str1` and `str2`
3+
var paths = {};
4+
5+
// Check the string lengths are the same to begin
6+
if ((str1 + str2).length !== combined.length) {
7+
return false;
178
}
18-
return true;
9+
10+
// Finding paths is essentially the anagrams solution
11+
(function findPath (str1, str2, path) {
12+
if (path.length === combined.length) { return paths[path] = true; }
13+
14+
// Find the next path from the first character of either strings
15+
str1 && findPath(str1.substr(1), str2, path + str1.substr(0, 1));
16+
str2 && findPath(str1, str2.substr(1), path + str2.substr(0, 1));
17+
})(str1, str2, '');
18+
19+
return combined in paths;
1920
};

0 commit comments

Comments
 (0)