-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1160.拼写单词.js
51 lines (47 loc) · 916 Bytes
/
1160.拼写单词.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
/*
* @lc app=leetcode.cn id=1160 lang=javascript
*
* [1160] 拼写单词
*/
// @lc code=start
/**
* @param {string[]} words
* @param {string} chars
* @return {number}
*/
/**
* hashMap
*/
var countCharacters = function(words, chars) {
let map = new Map();
for (let c of chars) {
if (map.has(c)) {
map.set(c, map.get(c) + 1);
} else {
map.set(c, 1);
}
}
return words
.filter(w => {
// clone Map
let nMap = new Map(map);
if (w.length > chars.length) {
return false;
} else {
for (let c of w) {
if (nMap.has(c)) {
if (nMap.get(c) === 1) {
nMap.delete(c);
} else {
nMap.set(c, nMap.get(c) - 1);
}
} else {
return false;
}
}
}
return true;
})
.reduce((s, w) => w.length + s, 0);
};
// @lc code=end