-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path748-Shortest-Completing-Word.js
43 lines (36 loc) · 1.06 KB
/
748-Shortest-Completing-Word.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
// 748. Shortest Completing Word [Easy]
// https://leetcode.com/problems/shortest-completing-word/
/**
* @param {string} licensePlate
* @param {string[]} words
* @return {string}
*/
const shortestCompletingWord = (licensePlate, words) => {
const letters = licensePlate
.split('')
.filter((char) => /[a-zA-Z]/.test(char))
.map((char) => char.toLowerCase())
.reduce((acc, char) => {
if (!acc[char]) acc[char] = 0;
acc[char] += 1;
return acc;
}, {});
const suitableWords = [];
words.forEach((word, idx) => {
const temp = { ...letters };
word.split('').forEach((letter) => {
if (temp[letter] !== undefined) {
temp[letter] -= 1;
}
});
const allLettersUsed = Object.values(temp).every((value) => value <= 0);
if (allLettersUsed) {
suitableWords.push({ word, idx });
}
});
suitableWords.sort((word1, word2) => {
if (word1.word.length === word2.word.length) return word1.idx - word2.idx;
return word1.word.length - word2.word.length;
});
return suitableWords[0].word;
};