赞
踩
给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写时,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。
提示:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
所有字符串中都仅包含小写英文字母
来源:力扣(LeetCode)
思路:依次遍历数组中的字符串,遍历这个字符串中的字符,在chars中寻找,如果存在就删除掉第一个字符,否则返回False。如果遍历完chars之后还有剩余字符,则返回True。
class Solution: def m(self, chars1:str, chars2:str)->bool: for i in chars1 : t = chars2.find(i) if t >= 0: #print(i) chars2 = chars2.replace(i,"", 1) else: return False if len(chars2)>=0: return True return False def countCharacters(self, words: List[str], chars: str) -> int: num = 0 for s in words: temp = chars #print(s) if self.m(s, temp): num = num+len(s) return num
思路:遍历words数组,对于其中的每一个字符串A,遍历chars中的每个字符分别在A中和chars中出现的数目,如果后者较大,则设flag为1,代表能够拼出A单词,否则记为0,表示不能包含此单词。最终累加长度。
class Solution(object):
def countCharacters(self, words, chars):
ans = 0
for w in words:
for i in w:
if w.count(i) <= chars.count(i):
flag = 1
continue
else:
flag = 0
break
if flag == 1:
ans+=len(w)
return ans
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。