给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
你可以按任意顺序返回答案。
示例
示例 1:
输入:[“bella”,”label”,”roller”]
输出:[“e”,”l”,”l”]
示例 2:
输入:[“cool”,”lock”,”cook”]
输出:[“c”,”o”]
解题
题目的意思就是取所有word里都有的字母
比如 “bella” 有 1个b 1个e 2个l 1个a
“label” 有 2个l 1个a 1个b 1个e
“roller” 有 1个r 1个o 2个l 1个e 1个r
这3个单词相交,得出都有 1个e 和 2个l
所以可以先把第一个单词拆解成一个个字母,记录字母个数,再遍历所有单词,与之对比字母个数,取交集。最后得出结果
/**
* @param {string[]} words
* @return {string[]}
*/
var commonChars = function(words) {
const list = new Array(26).fill(0)
for (let i = 0; i < words[0].length; i++) {
list[words[0][i].charCodeAt() - 97]++
}
for (let i = 1; i < words.length; i++) {
const arr = new Array(26).fill(0)
for (let j = 0; j < words[i].length; j++) {
arr[words[i][j].charCodeAt() - 97]++
}
for (let j = 0; j < 26; j++) {
list[j] = Math.min(list[j], arr[j])
}
}
const res = []
for (let i = 0; i < list.length; i++) {
if (list[i] > 0) {
for (let j = 0; j < list[i]; j++) {
res.push(String.fromCharCode(i + 97))
}
}
}
return res
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-common-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。