• 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
                    
  • 相关阅读:
    内部类
    抽象类与接口
    多态
    继承
    封装
    创建对象的内存分析
    构造器
    面向对象 类与对象
    uniapp跳转
    uniapp-组件引用错误,仅支持 import 方式引入组件
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13208555.html
Copyright © 2020-2023  润新知