-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathallconstruct.js
84 lines (65 loc) Β· 2.5 KB
/
allconstruct.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict';
function allConstruct(target, wordbank, memo = {}, err = true) {
if (target in memo) {
return memo[target];
}
if (target === '') {
return [[]];
}
let ways = [];
for (let word of wordbank) {
if (target.indexOf(word) === 0) {
//console.log({ suffix: target.slice(word.length) });
const suffix = target.slice(word.length);
const suffixes = allConstruct(suffix, wordbank, memo, false);
//console.log({ halfMeasures: suffixes });
const targets = suffixes.map(s => [word, ...s]);
ways.push(...targets);
console.log({ ways });
}
}
// for (let i = 0; i < wordbank.length; i++) {
// if (target.startsWith(wordbank[i])) {
// //console.log({ suffix2: target.slice(wordbank[i].length) });
// let halfMeasures = allConstruct(target.slice(wordbank[i].length), wordbank, memo, false);
// //console.log({ halfMeasures2: halfMeasures });
// halfMeasures.map(hm => {
// hm.unshift(wordbank[i]);
// ways.push(hm);
// return hm;
// });
// console.log({ ways });
// }
// }
// for (let i = 0; i < wordbank.length; i++) {
// if (target.startsWith(wordbank[i])) {
// let halfMeasures = allConstruct(target.slice(wordbank[i].length), wordbank, memo);
// halfMeasures.map(halfMeasure => {
// halfMeasure.unshift(wordbank[i]);
// ways.push(halfMeasure);
// return halfMeasure;
// });
// }
// // if (target.endsWith(wordbank[i])) {
// // let halfMeasures = allConstruct(target.slice(0, -wordbank[i].length), wordbank, memo);
// // halfMeasures.map(halfMeasure => {
// // halfMeasure.unshift(wordbank[i]);
// // ways.push(halfMeasure);
// // return halfMeasure;
// // });
// // }
// }
memo[target] = ways;
return memo[target];
};
console.log(allConstruct('abcdef', ['ab', 'abc', 'cd', 'def', 'abcd'])); // true
console.log(allConstruct('skateboard', ['bo', 'rd', 'ate', 't', 'boar'])); // false
console.log(allConstruct('enterapotentpot', ['a', 'p', 'ent', 'enter', 'ot', 'o', 't'])); // true
console.log(allConstruct('eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef', [
'e',
'ee',
'eee',
'eeee',
'eeeee',
'eeeeee'
])); // false