
20201014
给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
你可以按任意顺序返回答案。
输入:["bella","label","roller"]
输出:["e","l","l"]输入:["cool","lock","cook"]
输出:["c","o"]思路
通过哈希记录 A 这种子元素公共字符的数量:

抛砖引玉
/**
* @param {string[]} A
* @return {string[]}
*/
var commonChars = function(A) {
let map = new Map(),
_result = []
// 初始化基准map
for (let c of A[0]) {
map.has(c) ? map.set(c, map.get(c) + 1) : map.set(c, 1)
}
for (let i = 1; i < A.length; i++) {
// 统计后面字符数量
let nextMap = new Map()
for (let c of A[i]) {
nextMap.has(c) ? nextMap.set(c, nextMap.get(c) + 1) : nextMap.set(c, 1)
}
// 计算相同字符数量
for (let [key, value] of map) {
map.set(key, Math.min(value, nextMap.get(key) || 0))
}
}
// 拼接结果
for (let [key, value] of map) {
if (value) {
_result = _result.concat(Array.from({ length: value }).fill(key))
}
}
return _result
}var commonChars = function(A) {
// 初始化结果数组
let _result = A[0].split('')
for (let i = 1; i < A.length; i++) {
let item = A[i].split('')
// 过滤掉非公共字符
_result = _result.filter((c) => {
// 在后续元素中包含,注意为了避免一个元素重复查询某个字符则查询到包含后将该位置从数组中移除
const index = item.indexOf(c)
if (index > -1) {
item.splice(index, 1)
}
return index !== -1
})
}
return _result
}