[LeetCode]#1160. Find Words That Can Be Formed by Characters
2 min readJan 23, 2021
Environment: Python 3.8
Key technique: count
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.
Analysis:
- word=’cat’. c:1, a:1, t:1
- char=’atach’. c:1, a:2, t:1, h:1
- We don’t get any false, so return True.
Solution:
class Solution:
def countCharacters(self, words, chars):
flag = False
ans = 0
for word in words:
for char in word:
if word.count(char) <= chars.count(char):
flag = True
else:
flag = False
break
if flag == True:
ans += len(word)
return ans
Submissions:
Reference: