Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Words That Can Be Formed by Characters.py #896

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Words That Can Be Formed by Characters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from collections import defaultdict

class Solution(object):
def countCharacters(self, words, chars):
"""
:type words: List[str]
:type chars: str
:rtype: int
"""
chars_count = defaultdict(int)
for char in chars:
chars_count[char] += 1

result = 0

for word in words:
word_count = defaultdict(int)
for char in word:
word_count[char] += 1

if all(word_count[c] <= chars_count[c] for c in word_count):
result += len(word)

return result

# Example usage:
solution = Solution()
words_example1 = ["cat", "bt", "hat", "tree"]
chars_example1 = "atach"
print(solution.countCharacters(words_example1, chars_example1)) # Output: 6

words_example2 = ["hello", "world", "leetcode"]
chars_example2 = "welldonehoneyr"
print(solution.countCharacters(words_example2, chars_example2)) # Output: 10