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

Fatboy Slim
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:

  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.

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:

https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1020408/Super-simple-python-solution.-Faster-than-99

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet