给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
你可以按任意顺序返回答案。
示例 1:
输入:[“bella”,”label”,”roller”]
输出:[“e”,”l”,”l”]
示例 2:
输入:[“cool”,”lock”,”cook”]
输出:[“c”,”o”]
提示:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] 是小写字母
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-common-characters
思路:
统计每个单词每个字母出现的次数,肯定是对每个字母次数取最小,最后将字母重复丢进答案中。看了题解发现和官方是一个思路。
复杂度分析:
时间复杂度O(n*(m+26)) n是字符串数组A的长度,m是字符串平均长度
空间复杂度O(26)
var commonChars = function(A) {let n = A.length;let cnt = new Array(26).fill(n)let tmp = new Array(26).fill(0)for(let i = 0; i < n; i++){let str = A[i];for(let j = 0;j < str.length;j++){tmp[str.charCodeAt(j) - 97]++;}for(let j = 0;j<26;j++){cnt[j] = Math.min(tmp[j],cnt[j]);tmp[j] = 0;}}let ans = [];for(let j=0;j<26;j++){ans.push(...String.fromCharCode(97+j).repeat(cnt[j]).split(''))}return ans;};
