文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
**解析:**Version 1,使用Counter
统计字符出现的次数,然后进行比较。Version 2,直接使用字符串的count
方法统计字符出现的次数进行比较。
- Version 1
class Solution:def countCharacters(self, words: List[str], chars: str) -> int:candidates = Counter(chars)lengths = 0for word in words:good = Truetemp = Counter(word)for ch, num in temp.items():if ch not in candidates or temp[ch] - candidates[ch] > 0:good = Falsebreakif good:lengths += len(word)return lengths
- Version 2
class Solution:def countCharacters(self, words: List[str], chars: str) -> int:lengths = 0for word in words:good = Truefor ch in word:if word.count(ch) > chars.count(ch):good = Falsebreakif good:lengths += len(word)return lengths
Reference
- https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/