總的來說這周的題目較爲簡單,前兩道完全是拼手速的題目。
5048. 拼寫單詞
給你一份『詞彙表』(字符串數組) words
和一張『字母表』(字符串) chars
。
假如你可以用 chars
中的『字母』(字符)拼寫出 words
中的某個『單詞』(字符串),那麼我們就認爲你掌握了這個單詞。
注意:每次拼寫時,chars
中的每個字母都只能用一次。
返回詞彙表 words
中你掌握的所有單詞的 長度之和。
class Solution(object):
def countCharacters(self, words, chars):
"""
:type words: List[str]
:type chars: str
:rtype: int
"""
dic = {}
for s in chars:
dic[s] = dic.get(s,0)+1
count = 0
res = 0
for s in words:
dic1 = {}
for i in range(len(s)):
dic1[s[i]] = dic1.get(s[i],0)+1
if s[i] in chars and dic1[s[i]]<=dic[s[i]]:
count += 1
if count == len(s):
res += count
count = 0
return res
5052. 最大層內元素和
給你一個二叉樹的根節點 root
。設根節點位於二叉樹的第 1
層,而根節點的子節點位於第 2
層,依此類推。
請你找出層內元素之和 最大 的那幾層(可能只有一層)的層號,並返回其中 最小 的那個。
class Solution(object):
def maxLevelSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
flag = 0
stack = [root]
max1 = 0
a = 0
while stack:
stack1 = []
res = 0
while stack:
tep = stack.pop()
if tep.left:
stack1.append(tep.left)
if tep.right:
stack1.append(tep.right)
res += tep.val
flag += 1
if res > max1:
max1 = res
a = flag
stack = stack1
return a