Skip to content

Commit fb9c78b

Browse files
authored
Create word-break.js
1 parent b2f7e91 commit fb9c78b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

word-break.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
let dictionary = [
2+
"i",
3+
"like",
4+
"love",
5+
"sam",
6+
"sung",
7+
"samsung",
8+
"mobile",
9+
"ice",
10+
"cream",
11+
"icecream",
12+
"man",
13+
"and",
14+
"go",
15+
"mango"
16+
];
17+
18+
const presentInDictionary = input => {
19+
return dictionary.indexOf(input.join("")) !== -1;
20+
};
21+
22+
// the undo function not upto the mark
23+
const backtrack = (input, result = []) => {
24+
for (let i = 1; i < input.length; i++) {
25+
const left = input.slice(0, i);
26+
const rest = input.slice(i);
27+
28+
if (presentInDictionary(left)) {
29+
result.push(left.join(""));
30+
31+
if (presentInDictionary(rest)) {
32+
result.push(rest.join(""));
33+
console.log(result);
34+
result.pop();
35+
}
36+
backtrack(rest, result);
37+
result.pop();
38+
}
39+
}
40+
};
41+
42+
const input = "ilovesamsungmobile";
43+
const result = [];
44+
backtrack(input.split(""), result);
45+
// console.log(result);

0 commit comments

Comments
 (0)