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.
複製代碼