|
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) { |
7 | 4 | return false;
|
8 | 5 | }
|
9 | 6 |
|
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 | +}; |
13 | 9 |
|
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 | + } |
18 | 15 |
|
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