-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathword-break.js
45 lines (40 loc) · 841 Bytes
/
word-break.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
let dictionary = [
"i",
"like",
"love",
"sam",
"sung",
"samsung",
"mobile",
"ice",
"cream",
"icecream",
"man",
"and",
"go",
"mango"
];
const presentInDictionary = input => {
return dictionary.indexOf(input.join("")) !== -1;
};
// the undo function not upto the mark
const backtrack = (input, result = []) => {
for (let i = 1; i < input.length; i++) {
const left = input.slice(0, i);
const rest = input.slice(i);
if (presentInDictionary(left)) {
result.push(left.join(""));
if (presentInDictionary(rest)) {
result.push(rest.join(""));
console.log(result);
result.pop();
}
backtrack(rest, result);
result.pop();
}
}
};
const input = "ilovesamsungmobile";
const result = [];
backtrack(input.split(""), result);
// console.log(result);