-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproblem_022.js
More file actions
34 lines (31 loc) Β· 1.2 KB
/
problem_022.js
File metadata and controls
34 lines (31 loc) Β· 1.2 KB
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
/**
* Returns a possible reconstruction of a string with a word set.
* @param {string[]} array
* @return {string[]}
*/
const getReconstruction = (array) => {
const length = array.length;
let orderedList = {}
let orderedWord = array[length-1];
// Iterate until length - 1
for(let i = 0; i < length-1; i++) {
let indexOf = orderedWord.indexOf(array[i]);
let wordLength = array[i].length
// Places in order
orderedList[indexOf] = array[i];
// Removes word from string / duplicates
orderedWord = orderedWord.replace(array[i], ' '.repeat(wordLength));
}
let orderedArr = []
// Add to orderedArr, removing nonexistent values
for (var property in orderedList) {
if(property > -1) {
orderedArr.push(orderedList[property]);
}
}
return orderedArr;
}
getReconstruction(['quick', 'brown', 'the', 'fox', 'thequickbrownfox']); // ["the", "quick", "brown", "fox"]
getReconstruction(['bed', 'bath', 'bedbath', 'and', 'beyond', 'bedbathandbeyond']); // ["bed", "bath", "and", "beyond"]
getReconstruction(['home', 'best', 'buy', 'mart', 'bestbuy', 'bestbuy']); // ["best", "buy"]
getReconstruction(['quick', 'quick', 'the', 'brown', 'the', 'thequickbrown']); // ["the", "quick", "brown"]