给定一个字符串数组 words 和一个字符串 chars 如果一个字符串能被 chars 里面的字符组成那么这个字符串就是好的chars里面每个字符只能使用一次。求:words 里面所有好的字符串的字符总个数。比如:words = cat bt hat treechars = atach好的字符串有 cat hat 3 + 3 = 6输出:6
思路:
- 遍历words数组中的每个字符串,判断该字符串是否是好的字符串。
- 判断的方法是:使用一个字典counts记录chars中每个字符出现的次数。
- 对于每个字符串,使用一个新的字典temp_counts记录该字符串中每个字符出现的次数。
- 遍历字符串中的每个字符,将其加入temp_counts中。如果加入后temp_counts中该字符的次数超过了counts中该字符的次数,说明该字符串不是好的字符串,跳出循环。
- 如果遍历完成后,temp_counts中每个字符的次数都没有超过counts中该字符的次数,说明该字符串是好的字符串,将其长度加入结果中。
- 最后返回结果。
代码如下: def countCharacters(words, chars): counts = {} for char in chars: if char not in counts: counts[char] = 1 else: counts[char] += 1
result = 0
for word in words:
temp_counts = {}
for char in word:
if char not in temp_counts:
temp_counts[char] = 1
else:
temp_counts[char] += 1
valid = True
for char in temp_counts:
if char not in counts or temp_counts[char] > counts[char]:
valid = False
break
if valid:
result += len(word)
return result
测试样例: words = ["cat", "bt", "hat", "tree"] chars = "atach" print(countCharacters(words, chars)
原文地址: https://www.cveoy.top/t/topic/ipFG 著作权归作者所有。请勿转载和采集!