zoukankan      html  css  js  c++  java
  • 1160. Find Words That Can Be Formed by Characters

    You are given an array of strings words and a string chars.

    A string is good if it can be formed by characters from chars (each character can only be used once).

    Return the sum of lengths of all good strings in words.

    1. 1 <= words.length <= 1000
    2. 1 <= words[i].length, chars.length <= 100
    3. All strings contain lowercase English letters only.

    开一个计数数组count,统计chars里每个字符出现的次数,然后for一遍words,word出现的字符计数-1,看看是否有的字符的计数小于0了,小于0就作废,不小于0就加长度。

    class Solution(object):
        def countCharacters(self, words, chars):
            """
            :type words: List[str]
            :type chars: str
            :rtype: int
            """
            count = [0] * 26
            ans = 0
            for c in chars:
                count[ord(c) - ord('a')] += 1
            for s in words:
                cp_count = [value for value in count]
                length = 0
                for c in s:
                    if cp_count[ord(c) - ord('a')] > 0:
                        length += 1
                        cp_count[ord(c) - ord('a')] -= 1
                    else:
                        length = 0
                        break
                ans += length
            return ans
                    
  • 相关阅读:
    [bzoj1797] [Ahoi2009]Mincut 最小割
    [bzoj3343] 教主的魔法
    [bzoj3702] 二叉树
    [bzoj3809] Gty的二逼妹子序列
    JavaScript的面向对象原理之原型链
    javaScript操作DOM深入理解
    BOM浏览器对象模型
    JavaScript
    DAO模式
    使用ADO.NET访问数据库
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13208555.html
Copyright © 2011-2022 走看看