Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.php
You may return the answer in any order. Example 1:ios
Input: ["bella","label","roller"]
Output: ["e","l","l"]
复制代码
Example 2:微信
Input: ["cool","lock","cook"]
Output: ["c","o"]
复制代码
Note:less
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] is a lowercase letter
复制代码
这里的题意比较简单,只要在 A 中的每一个字符串有相同的数量的字符个数,就都放到结果列表中。yii
class Solution(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
result = []
func = map(lambda x:collections.Counter(x), A)
for i in range(26):
c = chr(ord('a')+i)
num = min([count[c] for count in func])
if num:
result+=[c]*num
return result
复制代码
Runtime: 76 ms, faster than 20.19% of Python online submissions for Find Common Characters.
Memory Usage: 12.1 MB, less than 6.07% of Python online submissions for Find Common Characters.
复制代码
上面是遍历了 a-z 的全部字母,可是字符串中可能只须要遍历几个便可,因此能够换一下思路,只找第一个字符串中所包含的字母,这样能够大大缩短期。svg
class Solution(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
check = set(A[0])
tmp = [[l] * min([a.count(l) for a in A]) for l in check]
result = []
for i in tmp:
result+=i
return result
复制代码
Runtime: 24 ms, faster than 99.25% of Python online submissions for Find Common Characters.
Memory Usage: 11.9 MB, less than 61.10% of Python online submissions for Find Common Characters.
复制代码