LeetCode 1160. Find Words That Can Be Formed by Characters (Easy))

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.

Solution:

from collections import Counter
class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        count_chars = Counter(chars)
        ans = 0
        for word in words:
            count_word = Counter(word)
            for c, cnt in count_word.items():
                if cnt > count_chars[c]:
                    break
            else:
                ans += len(word)
        return ans

Explanation:

We need to check if the frequency of each char of each word satisfies the available frequency that chars can provide. In other words, if the current word has a char that has a higher frequency than (say "hello" needs two "l" while we only have one "l" in "helo", we need to skip this word. We will only count and sum the length of a word that if finish the loop of every character of a word)
我们需要检查每个单词的每个字符的频率是否满足字符可以提供的可用频率。换句话说,如果当前单词的字符频率高于(例如,“ hello”需要两个“ l”,而“ helo”中只有一个“ l”,那么我们需要跳过该单词)。计算并求和一个单词的长度,如果完成一个单词的每个字符的循环,则该单词的长度

你可能感兴趣的:(LeetCode 1160. Find Words That Can Be Formed by Characters (Easy)))