leetcode 1160 python

mac2026-08-29  8

题目要求: https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/ python中all函数用法: all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。 元素除了是 0、空、None、False 外都算 True。 思路: 直接统计字母表 chars 中每个字母出现的次数,然后检查词汇表 words 中的每个单词,如果该单词中每个字母出现的次数都小于等于词汇表中对应字母出现的次数,就将该单词长度加入答案中。

class Solution: def countCharacters(self, words: List[str], chars: str) -> int: ans = 0 cnt = collections.Counter(chars) for w in words: c = collections.Counter(w) if all([c[i] <= cnt[i] for i in c]): ans += len(w) return ans
最新回复(0)