[leetcode] 953. Verifying an Alien Dictionary
1160
2022-08-22
[leetcode] 1160. Find words That Can Be Formed by Characters
Description
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.
Example 1:
Input: words = ["cat","bt","hat","tree"], chars = "atach"Output: 6Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Example 2:
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"Output: 10Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
Note:
1 <= words.length <= 1000.1 <= words[i].length, chars.length <= 100.All strings contain lowercase English letters only.
分析
题目的意思是:给定一个数组和一个字符串,问数组里面的单词能否由给定的字符串构成,把所有的满足条件的字符串找到,返回总长度。这是一道easy的题目,用了python的counter统计chars的词频,然后再遍历统计字符串数组中每个单词的词频,找到满足条件的即可。这是笨办法,不排除有其他更好的解法。
代码
class Solution: def countCharacters(self, words: List[str], chars: str) -> int: counter=collections.Counter(chars) res=0 for word in words: cnt_dict={} for ch in word: if(ch in cnt_dict): cnt_dict[ch]+=1 else: cnt_dict[ch]=1 flag=True for k,v in cnt_dict.items(): cnt=counter[k] if(v>cnt): flag=False break if(flag): res+=len(word) return res
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~