leetcode系列–第1002题.查找共用字符
给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),
并以数组形式返回。你可以按 任意顺序 返回答案。
示例 1:
输入:words = ["bella","label","roller"]
输出:["e","l","l"]
示例 2:
输入:words = ["cool","lock","cook"]
输出:["c","o"]
var commonChars = function (words) {
let result = []
let firstHash = new Array(26).fill(0);
let arr0 = words[0]
let base = "a".charCodeAt();
for (let i of arr0) {
firstHash[i.charCodeAt() - base]++
}
for (let i = 1; i < words.length; i++) {
let otherHash = new Array(26).fill(0);
for (let j = 0; j < words[i].length; j++) {
let idx = words[i][j].charCodeAt() - base;
otherHash[idx] += 1
}
for (let i = 0; i < 26; i++) {
firstHash[i] = Math.min(firstHash[i], otherHash[i])
}
}
for (let i = 0; i < 26; i++) {
while (firstHash[i] > 0) {
result.push(String.fromCharCode(i + base))
firstHash[i] -= 1
}
}
return result
};