-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgreedy_algorithm.js
More file actions
75 lines (72 loc) · 1.94 KB
/
Copy pathgreedy_algorithm.js
File metadata and controls
75 lines (72 loc) · 1.94 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
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
/*
* Given a string {letters} and a set of {words}.
* Find the longest word in {words} that is subsequence of {letters}
*
* O(N + L * log N)
*
* @param words {array}
* @param letters {string}
* @return {string | -1}
*/
function longestWord(words, letters) {
const letterPositions = getLetterPositions(letters);
// Sorted words by length O(N)
words = words.sort((a,b) => {
return a.length < b.length;
});
console.log(words);
// O(N words * L averange length);
for (let i = 0; i < words.length; i++) {
const word = words[i];
const wordLettersPosition = getLetterPositions(word);
for (let k = 0; k < word.length; k++) {
const letter = word[k];
if (!letterPositions[letter]) {
break;
}
if (wordLettersPosition[letter].length > letterPositions[letter].length) {
break;
}
if (k === word.length - 1) {
return word;
}
}
}
return -1;
}
/*
* Generate hash object of {letters} positions
*
* O(N letters) space and speed
*
* @param letters {string}
* @return {object}
*/
function getLetterPositions(letters) {
const letterPositions = {};
for (let i = 0; i < letters.length; i++) {
const letter = letters[i];
if (!letterPositions[letter]) {
letterPositions[letter] = [];
}
letterPositions[letter].push(i);
}
return letterPositions;
}
/*
* Test function with console.log response
* @param desc {string}
* @param input {string}
* @param expect {string}
* return {print text}
*/
function it(desc, input, expect) {
console.log(`Starting testing: ${desc}`);
if (input === expect) {
return console.log(' => PASSED');
}
console.log(' => FAILED', input, expect);
}
console.log(longestWord(['apple', 'aa', 'ppp', 'blabla'], 'applee'));
it('#1 Find apple', longestWord(['apple', 'aa', 'ppp', 'blabla'], 'applee'), 'apple');
it('#2 Find bla', longestWord(['apple', 'aa', 'ppp', 'blabla', 'bla'], 'apleebla'), 'bla');