[LeetCode]#1160. Find Words That Can Be Formed by Characters

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.
  1. word=’cat’. c:1, a:1, t:1
  2. char=’atach’. c:1, a:2, t:1, h:1
  3. We don’t get any false, so return True.
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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store