来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-common-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
示例 1:
输入:words = ["bella","label","roller"]
输出:["e","l","l"]
示例 2:
输入:words = ["cool","lock","cook"]
输出:["c","o"]
提示:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] 由小写英文字母组成
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
# 统计每个字符的26个字母的出现频次,保存最小的频次
# 使用长度26的列表进行计算,第一步对第一个字符串进行统计
temp = [0]*26
for char in words[0]:
temp[ord(char)-ord("a")] += 1
# 对所有的字符串进行统计,然后与temp中频次相比,保留最小值
for word in words:
temp1 = [0] * 26
for char in word:
temp1[ord(char)-ord("a")] +=1
for i in range(26):
temp[i] = min(temp[i], temp1[i])
# 生成数组
chrs = []
for i in range(26):
if(temp[i]!=0):
chrs = chrs + (temp[i] * [chr(i+ord("a"))])
return chrs