給你一份『詞彙表』(字符串數組) 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)
Python3 1
思路:依次遍歷數組中的字符串,遍歷這個字符串中的字符,在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
Python3 2
思路:遍歷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