-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsolution.js
52 lines (45 loc) · 933 Bytes
/
solution.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
/**
* Check if the word is within charMap.
* @param {*} word
* @param {*} charMap
*/
const isWordInCharMap = (word, charMap) => {
const wMap = new Map()
const ws = word.split('')
for (const w of ws) {
if (wMap.has(w)) {
wMap.set(w, wMap.get(w) + 1)
} else {
wMap.set(w, 1)
}
if (
(!charMap.get(w)) ||
(wMap.get(w) > charMap.get(w))
) {
return false
}
}
return true
}
/**
* @param {string[]} words
* @param {string} chars
* @return {number}
*/
const countCharacters = function (words, chars) {
const charMap = new Map()
chars.split('').forEach((c) => {
if (charMap.has(c)) {
charMap.set(c, charMap.get(c) + 1)
} else {
charMap.set(c, 1)
}
})
const length = words.reduce((acc, cur) => {
return isWordInCharMap(cur, charMap)
? acc + cur.length
: acc
}, 0)
return length
}
module.exports = countCharacters