可以用 Python 来解决这个问题。思路如下:
-
统计
chars
中每个字母的出现次数。 -
遍历
words
列表,检查每个单词是否可以由chars
中的字母拼出(即单词中的每个字母数量不能超过chars
中对应的数量)。 -
如果单词可以拼出,就累加它的长度。
代码实现如下:
from collections import Counter
def countCharacters(words, chars):
char_count = Counter(chars) # 统计 chars 中每个字母的个数
total_length = 0
for word in words:
word_count = Counter(word) # 统计 word 中每个字母的个数
if all(word_count[char] <= char_count.get(char, 0) for char in word):
total_length += len(word) # 累加满足条件的单词长度
return total_length
# 示例
words = ["cat", "bt", "hat", "tree"]
chars = "atach"
print(countCharacters(words, chars)) # 输出 6
解释:
-
Counter(chars)
统计chars
中的字符出现次数,如"atach"
→{'a': 2, 't': 1, 'c': 1, 'h': 1}
-
遍历
words
中的每个单词,统计单词的字符频率,确保所有字符数量都在chars
允许的范围内。 -
如果符合条件,则累加单词长度。
这个方法的时间复杂度是 O(N*M),其中 N
是 words
的长度,M
是单词的平均长度,适用于一般规模的数据。