题目如下:
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.You may return the answer in any order.
Example 1:
Input: ["bella","label","roller"] Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"] Output: ["c","o"]
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j]
is a lowercase letter
解题思路:创建一个char_count[26]数字,记录a-z每一个字符在所有字符串中出现的最少的次数,初始值为101。接下来遍历Input中的每个单词,并且把每个字符在这个单词出现的次数与char_count中对应字符的次数进行比较取较小值。Input遍历完成后,char_count中每个字符所对应的值即为公共的个数。
代码如下:
class Solution(object): def commonChars(self, A): """ :type A: List[str] :rtype: List[str] """ cl = [101] * 26 for word in A: for char in range(97,97+26): inx = char - ord('a') cl[inx] = min(cl[inx],word.count(chr(char))) res = [] for i in range(len(cl)): res += [chr(i + ord('a'))] * cl[i] return res