思路: 第一个字符串全部字符加入 ans,后面的字符串检测是不是在里面是的话,tmp就+1,并且将这个公共的部分tmp作为ans开始下一次
# 给定仅有小写字母组成的字符串数组 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] 是小写字母
#
# Related Topics 数组 哈希表
# 👍 118 👎 0
# 1002.查找常用字符
# 思路: 第一个字符串全部字符加入 ans,后面的字符串检测是不是在里面是的话,不是0就-1,最后移除所有不为0的k-v对
# 并且将这个公共的部分作为ans开始下一次
# leetcode submit region begin(Prohibit modification and deletion)
import collections
from typing import List
import copy
class Solution:
def commonChars(self, A: List[str]) -> List[str]:
ans = collections.defaultdict(int)
ans_list = []
for indexi, i in enumerate(A):
tmp = collections.defaultdict(int)
for j in i:
if indexi == 0:
tmp[j] += 1 # 第一轮
else:
if j in ans and ans[j] != 0:
tmp[j] += 1
ans[j] -= 1
ans = tmp
for i in ans:
for j in range(ans[i]):
ans_list.append(i)
return ans_list
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
sol = Solution()
print(sol.commonChars(["bella", "label", "roller"]))
print(sol.commonChars(["cool", "lock", "cook"]))
print(sol.commonChars([]))
题解里面大佬的答案,妙啊。
大致思路是:用key值[HashSet]在所有的字符串里面数一下有多少个,取最少的。
class Solution(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
res = []
if not A:
return res
key = set(A[0])
for k in key:
minnum = min(a.count(k) for a in A)
res += minnum * k
return res