LeetCode1160.找出可以由字符组成的单词拼写单词【易】【Python】【字符串】问题LeetCode给你一个字符串数组words和一个字符串chars。可以由chars中的字符组成(每个字符只能使用一次)。返回单词中所有好字符串的长度总和。示例1:输入:words=["cat","bt","hat","tree"],chars="atach"输出:6解释:可以组成的字符串是"cat"和"hat"所以answeris3+3=6.Example2:Input:words=["hello","world","leetcode"],chars="welldonehoneyr"Output:10Explanation:可以组成的字符串是"hello"和"world"所以答案是5+5=10。注意:1<=words.length<=10001<=words[i].length,chars.length<=100所有字符串只包含小写英文字母。题目会给你一个“vocabulary”(字符串数组)words和一个“lettertable”(字符串)chars。如果你能用chars中的“letters”(字符)拼出words中的“word”(字符串),那么我们认为你已经掌握了这个词。注意:chars中的每个字母每次拼写只能使用一次。返回词汇表words中所有单词的长度总和。示例1:输入:words=["cat","bt","hat","tree"],chars="atach"输出:6解释:可以组成字符串“cat”和“hat”,所以答案是3+3=6。示例2:输入:words=["hello","world","leetcode"],chars="welldonehoneyr"输出:10解释:字符串"hello"和"world"可以是形成,所以答案是5+5=10。Tips:1<=words.length<=10001<=words[i].length,chars.length<=100所有字符串只包含小写英文字母ideastringsolution1Usecollections,代码风格比较pythonic。Python3代码输入importListclassSolution:defcountCharacters(self,words:List[str],chars:str)->int:#solutiononeimportcollectionsres=0cnt=collections.Counter(chars)forwordinwords:c=collections.Counter(word)ifall([c[i]<=cnt[i]foriinc]):res+=len(word)returnres解2判断word的字符数是否<=chars中这些字符的数量。Python3代码输入importListclassSolution:defcountCharacters(self,words:List[str],chars:str)->int:#solutiontwores=0forwordinwords:n=len(word)cnt=0foriinword:#thecharactersiinword<=thenumberofcharactersiincharsifword.count(i)<=chars.count(i):cnt+=1else:break#word可以拼出charsifcnt==n:res+=cnt返回res代码地址GitHub链接
