给定仅有小写字母组成的字符串数组 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1
字典操作
class Solution(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
dict={}
result=""
for i in A[0]:
dict.setdefault(i,0)
dict[i]+=1
if len(A)==1:
return [i for i in A]
for i in range(1,len(A)):
for k,v in dict.items():
if k not in A[i]:
dict[k]=0
else:
if v>A[i].count(k):
dict[k]=A[i].count(k)
for k,v in dict.items():
result+=k*v
return [i for i in result]
执行结果:
通过
显示详情
执行用时 :28 ms, 在所有 Python 提交中击败了91.47%的用户
内存消耗 :12.9 MB, 在所有 Python 提交中击败了100.00%的用户
思路2
通过内置Counter实现
class Solution(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
if not A:
return A
res=Counter(A[0])
for i in range(1,len(A)):
res=res&Counter(A[i])
return list(res.elements())
执行结果:
通过
显示详情
执行用时:80 ms, 在所有 Python 提交中击败了10.62%的用户
内存消耗:13 MB, 在所有 Python 提交中击败了100.00%的用户
思路3
将列表第一个字符串集合操作,用取得的字母统计列表中每个字符串中出现该字母的最小个数后完成拼接
class Solution(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
if not A:
return A
tmp=set(A[0])
res=""
for i in tmp:
res+=i*min([j.count(i) for j in A])
return list(res)
执行结果:
通过
显示详情
执行用时:36 ms, 在所有 Python 提交中击败了70.80%的用户
内存消耗:12.7 MB, 在所有 Python 提交中击败了100.00%的用户