标签:return 单词 出现 temp 方法 etc turn form 循环
1160. Find Words That Can Be Formed by Characters
先把可使用的所有字符放入字典charscount,以“字符:可出现次数”的形式存放,然后遍历words中的每个单词,初始化tempcount字典为charscount的副本,再依次遍历字母,如果当前字母不在tempcount中,或者可使用次数为0,则break掉并设置当前字符串长度贡献为0,每次字母层遍历结束后都把当前字符串的长度贡献加到返回值rat中,直到循环结束。
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
charscount = {}
for i in chars:
if i in charscount:
charscount[i] += 1
else:
charscount[i] = 1
rat = 0
for word in words:
templen = 0
tempcount = charscount.copy()
for letter in word:
if letter not in tempcount or not tempcount[letter]:
templen = 0
break
else:
tempcount[letter] -= 1
templen += 1
rat += templen
return rat
LeetCode #1160. Find Words That Can Be Formed by Characters
标签:return 单词 出现 temp 方法 etc turn form 循环
原文地址:https://www.cnblogs.com/RatsCommander/p/14029959.html