mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
更新1002. 查找常用字符,js方法采用map
This commit is contained in:
@ -252,6 +252,36 @@ var commonChars = function (words) {
|
||||
}
|
||||
return res
|
||||
};
|
||||
|
||||
// 方法二:map()
|
||||
var commonChars = function(words) {
|
||||
let min_count = new Map()
|
||||
// 统计字符串中字符出现的最小频率,以第一个字符串初始化
|
||||
for(let str of words[0]) {
|
||||
min_count.set(str, ((min_count.get(str) || 0) + 1))
|
||||
}
|
||||
// 从第二个单词开始统计字符出现次数
|
||||
for(let i = 1; i < words.length; i++) {
|
||||
let char_count = new Map()
|
||||
for(let str of words[i]) { // 遍历字母
|
||||
char_count.set(str, (char_count.get(str) || 0) + 1)
|
||||
}
|
||||
// 比较出最小的字符次数
|
||||
for(let value of min_count) { // 注意这里遍历min_count!而不是单词
|
||||
min_count.set(value[0], Math.min((min_count.get(value[0]) || 0), (char_count.get(value[0]) || 0)))
|
||||
}
|
||||
}
|
||||
// 遍历map
|
||||
let res = []
|
||||
min_count.forEach((value, key) => {
|
||||
if(value) {
|
||||
for(let i=0; i<value; i++) {
|
||||
res.push(key)
|
||||
}
|
||||
}
|
||||
})
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
TypeScript
|
||||
|
Reference in New Issue
Block a user