码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-11-27 11:39:59      阅读:10      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!