leetcode 1002. Find Common Characters( Python )

1,426 阅读20分钟

描述

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

解析

这里的题意比较简单,只要在 A 中的每个字符串有相同的数量的字符个数,就都放到结果列表中。

解答

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 的所有字母,但是字符串中可能只需要遍历几个即可,所以可以换一下思路,只找第一个字符串中所包含的字母,这样可以大大缩短时间。

解答

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.	
感谢支持 支付宝

支付宝

微信

微信