Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d8cced6

Browse files
committedSep 29, 2015
Improved compute time of combine strings solution
1 parent e146498 commit d8cced6

File tree

1 file changed

+32
-15
lines changed

1 file changed

+32
-15
lines changed
 
Lines changed: 32 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,37 @@
1-
module.exports = 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) {
1+
module.exports = function combineTwoStrings (str1, str2, str3) {
2+
// Simple optimisation to break when impossible.
3+
if ((str1.length + str2.length) !== str3.length) {
74
return false;
85
}
96

10-
// Finding paths is essentially the anagrams solution
11-
(function findPath (str1, str2, path) {
12-
if (path.length === combined.length) { return paths[path] = true; }
7+
return isCombineTwoStrings(str1, str2, str3);
8+
};
139

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, '');
10+
function isCombineTwoStrings (str1, str2, str3) {
11+
// No more solutions to find.
12+
if (str3.length === 0) {
13+
return true;
14+
}
1815

19-
return combined in paths;
20-
};
16+
var newStr3 = str3.substr(1);
17+
18+
// Path for when the first string matches.
19+
if (str1[0] === str3[0]) {
20+
// When both paths are possible, we implement a simple backtracking
21+
// mechanism for when the first was wrong. E.g. `aac`, `aab`, `aaacab`.
22+
if (str2[0] === str3[0]) {
23+
return isCombineTwoStrings(str1.substr(1), str2, newStr3) ||
24+
isCombineTwoStrings(str1, str2.substr(1), newStr3);
25+
}
26+
27+
return isCombineTwoStrings(str1.substr(1), str2, newStr3);
28+
}
29+
30+
// Path for when the second string matches.
31+
if (str2[0] === str3[0]) {
32+
return isCombineTwoStrings(str1, str2.substr(1), newStr3);
33+
}
34+
35+
// When neither path is possible, the combination is `false`.
36+
return false;
37+
}

0 commit comments

Comments
 (0)
This repository has been archived.