1002. 查找共用字符【简单】
1. 📝 题目描述
给你一个字符串数组 words,请你找出所有在 words 的每个字符串中都出现的共用字符(包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
示例 1:
txt
输入:words = ["bella","label","roller"]
输出:["e","l","l"]1
2
2
示例 2:
txt
输入:words = ["cool","lock","cook"]
输出:["c","o"]1
2
2
提示:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]由小写英文字母组成
2. 🎯 s.1 - 暴力解法
js
/**
* @param {string[]} words
* @return {string[]}
*/
var commonChars = function (words) {
// 统计第一个单词中每个字符出现的次数
const minCount = new Array(26).fill(0)
for (let char of words[0]) {
minCount[char.charCodeAt(0) - 'a'.charCodeAt(0)]++
}
// 遍历其余单词,更新每个字符的最小出现次数
for (let i = 1; i < words.length; i++) {
const currentCount = new Array(26).fill(0)
// 统计当前单词中每个字符出现的次数
for (let char of words[i]) {
currentCount[char.charCodeAt(0) - 'a'.charCodeAt(0)]++
}
// 更新每个字符在所有单词中的最小出现次数
for (let j = 0; j < 26; j++) {
minCount[j] = Math.min(minCount[j], currentCount[j])
}
}
// 根据最小出现次数构建结果数组
const result = []
for (let i = 0; i < 26; i++) {
for (let j = 0; j < minCount[i]; j++) {
result.push(String.fromCharCode(i + 'a'.charCodeAt(0)))
}
}
return result
}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
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