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
.
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
- All strings contain lowercase English letters only.
开一个计数数组count,统计chars里每个字符出现的次数,然后for一遍words,word出现的字符计数-1,看看是否有的字符的计数小于0了,小于0就作废,不小于0就加长度。
class Solution(object): def countCharacters(self, words, chars): """ :type words: List[str] :type chars: str :rtype: int """ count = [0] * 26 ans = 0 for c in chars: count[ord(c) - ord('a')] += 1 for s in words: cp_count = [value for value in count] length = 0 for c in s: if cp_count[ord(c) - ord('a')] > 0: length += 1 cp_count[ord(c) - ord('a')] -= 1 else: length = 0 break ans += length return ans