<p>You are given an array of strings <code>words</code> and a string <code>chars</code>.</p>

<p>A string is <strong>good</strong> if it can be formed by characters from <code>chars</code> (each character can only be used once).</p>

<p>Return <em>the sum of lengths of all good strings in words</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> words = [&quot;cat&quot;,&quot;bt&quot;,&quot;hat&quot;,&quot;tree&quot;], chars = &quot;atach&quot;
<strong>Output:</strong> 6
<strong>Explanation:</strong> The strings that can be formed are &quot;cat&quot; and &quot;hat&quot; so the answer is 3 + 3 = 6.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> words = [&quot;hello&quot;,&quot;world&quot;,&quot;leetcode&quot;], chars = &quot;welldonehoneyr&quot;
<strong>Output:</strong> 10
<strong>Explanation:</strong> The strings that can be formed are &quot;hello&quot; and &quot;world&quot; so the answer is 5 + 5 = 10.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= words.length &lt;= 1000</code></li>
	<li><code>1 &lt;= words[i].length, chars.length &lt;= 100</code></li>
	<li><code>words[i]</code> and <code>chars</code> consist of lowercase English letters.</li>
</ul>

from collections import Counter

class Solution:
    def countCharacters(self, words, chars):
        # Count the frequency of each character in 'chars'
        chars_count = Counter(chars)
        total_length = 0
        
        # Iterate through each word
        for word in words:
            word_count = Counter(word)
            
            # Check if we can form the word with 'chars'
            can_form = True
            for char in word_count:
                if word_count[char] > chars_count.get(char, 0):
                    can_form = False
                    break
            
            # If we can form the word, add its length to the total
            if can_form:
                total_length += len(word)
        
        return total_length

# Test cases
if __name__ == "__main__":
    sol = Solution()

    # Test case 1
    words1 = ["cat", "bt", "hat", "tree"]
    chars1 = "atach"
    result1 = sol.countCharacters(words1, chars1)
    print(result1)  # Expected output: 6 ("cat" and "hat" can be formed)

    # Test case 2
    words2 = ["hello", "world", "leetcode"]
    chars2 = "welldonehoneyr"
    result2 = sol.countCharacters(words2, chars2)
    print(result2)  # Expected output: 10 ("hello" and "world" can be formed)

143