leetcode 1160. Find Words That Can Be Formed by Characters(python)

318 阅读1分钟

描述

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.

Example 1:

Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: 
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.	

Example 2:

Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: 
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.

Note:

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

解析

根据题意,只要找出 words 中的 good 字符串然后将它们的长度相加即可。遍历 words 中的每个单词,然后遍历每个单词 word 的每个字符 c ,如果该字符 c 在 word 中出现的次数超过在 char 中的出现次数,则跳过该单词,直接去判断下一个单词;如果该单词是 good 的,则将长度追加到 res 中,继续进行下一个单词的判断,遍历结束即可得到答案

解答

class Solution(object):
def countCharacters(self, words, chars):
    """
    :type words: List[str]
    :type chars: str
    :rtype: int
    """
    res = 0
    for word in words:
        boolean = True
        for c in word:
            if word.count(c) > chars.count(c):
                boolean = False
                break
        if boolean:
            res += len(word)
    return res
		

运行结果

Runtime: 72 ms, faster than 94.16% of Python online submissions for Find Words That Can Be Formed by Characters.
Memory Usage: 14.3 MB, less than 29.18% of Python online submissions for Find Words That Can Be Formed by Characters.

原题链接:leetcode.com/problems/fi…

您的支持是我最大的动力