LeetCode #1160. Find Words That Can Be Formed by Characters

题目

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
            
posted @ 2020-11-24 14:02  老鼠司令  阅读(73)  评论(0)    收藏  举报