Find Words That Can Be Formed by Characters

Here’s a method to determine the sum of lengths of all good strings in words.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        # We create a count of characters in chars
        chars_count = {}
        for char in chars:
            chars_count[char] = chars_count.get(char, 0) + 1

        # Initialize a variable to store the total length of good words
        total_length = 0

        # Iterate through each word in words
        for word in words:
            # Make a copy of the chars_count
            temp_count = chars_count.copy()
            # Check if the word can be formed using the chars
            can_form_word = True
            for char in word:
                if temp_count.get(char, 0) > 0:
                    temp_count[char] -= 1
                else:
                    # If char is not present in temp_count or its count is 0, we can't form the word
                    can_form_word = False
                    break
            # If the word can be formed, add its length to the total length
            if can_form_word:
                total_length += len(word)

        return total_length

This method constructs a dictionary to count the frequency of each character in chars, then iterates through each word in words. For each word, it checks if it can be formed using the characters in chars by referencing the character count dictionary and updates the total length accordingly. Finally, it returns the total length of all good strings.