zoukankan      html  css  js  c++  java
  • 【leetcode】1002. Find Common Characters

    题目如下:

    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. 1 <= A.length <= 100
    2. 1 <= A[i].length <= 100
    3. 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
  • 相关阅读:
    Intellij IDEA使用restclient测试
    jmeter测试
    Java中String为什么是不可变的
    为什么String类是不可变的?
    反射中getMethods 与 getDeclaredMethods 的区别
    MD5加密
    将long型转换为多少MB的方法
    ContentProvider往通讯录添加联系人和获取联系人
    安卓软件版本更新
    Servlet生命周期与工作原理
  • 原文地址:https://www.cnblogs.com/seyjs/p/10469273.html
Copyright © 2011-2022 走看看