0226leetcode brushes 5 python questions

145

Title description:
Given a binary tree, return its post-order traversal.

Example:
Insert picture description here
Answer:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        res,st,r,prev=[],[],root,None

        while r or st:
            #  一直往左走
            while r:
                st.append(r)
                r=r.left
            #  走到底,弹出栈顶
            r=st.pop()
            #  如果该节点的没有右节点或者右节点已经访问过
            #  则访问该节点,并且让r指向空,
            #  因为访问过该节点后,该节点的左子树必定访问过,
            #  不应再往左节点走,而是再弹出栈顶元素
            if not r.right or r.right==prev:
                res.append(r.val)
                prev = r
                r = None
            #  否则,再次入栈,访问右节点
            else:
                st.append(r)
                r = r.right
        return res

856

Title description:
Given a balanced bracket string S, calculate the score of the string according to the following rules:
() 1 point.
AB gets A + B points, where A and B are balanced bracket strings.
(A) gets 2 * A points, where A is a balanced bracket string.

Example:
Insert picture description here
Answer:

class Solution:
    def scoreOfParentheses(self, S: str) -> int:
        '''
        #eval( )函数,用于去掉字符串上的引号
        return eval(S.replace(')(',')+(').replace('()','1').replace('(','2*('))
        '''
        '''
        s = ''
        for i in range(len(S)-1):
            if S[i] == '(':
                if S[i+1] == "(": 
                    s += "("
                else:
                    s += '1'
            else:
                if S[i+1] == '(':
                    s += '+'
                else:
                    s += ')*2'
        return eval(s)
        '''
        stack = [0]
        for c in S:
            if c == "(": # "("入栈
                stack.append(0)
            else:
                last = stack.pop()
                if last == 0: # "()"情况
                    stack[-1] += 1
                else: # "(A)" "AB" 情况
                    stack[-1] += 2 * last
        return stack.pop()

1003

Title description:
Give you a string s, please judge whether it is valid.
The string s is valid and needs to be satisfied: assuming that there is an empty string t = "" at the beginning, you can perform any of the following operations to convert t to s:
insert the string "abc" at any position in t. Formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note that tleft and tright may be empty.
If the string s is valid, return true; otherwise, return false.

Example:
Insert picture description here
Answer:

class Solution:
    def isValid(self, s: str) -> bool:
        '''
        while s!=''and 'abc'in s:
            s=s.replace('abc','')
        return s==''
        '''
        res=[]
        for i in s:
            if len(res)<2:
                res.append(i)
            elif i=='c' and res[-1]=='b' and res[-2]=='a':
                res.pop()
                res.pop()
            else:
                res.append(i)
        return len(res)==0

1130

Title description:
Give you an array of positive integers arr, consider all binary trees that meet the following conditions:
each node has 0 or 2 child nodes.
The value in the array arr corresponds to the value of each leaf node in the in-order traversal of the tree. (Knowledge review: If a node has 0 child nodes, then the node is a leaf node.)
The value of each non-leaf node is equal to the product of the maximum value of the leaf node in its left subtree and right subtree.
In all such binary trees, return the smallest possible sum of the values ​​of each non-leaf node. The value of this sum is a 32-bit integer.

Example:
Insert picture description here
Answer:

class Solution:
    def mctFromLeafValues(self, arr: List[int]) -> int:
        stack = []
        mct = 0
        for num in arr:
            while stack and num > stack[-1]:
                min_1 = stack.pop()
                if stack:
                    min_2 = min(stack[-1],num)
                else:
                    min_2 = num
                mct = mct + min_1 * min_2
            
            stack.append(num)
        
        while len(stack) > 1:
            mct = mct + stack.pop() * stack[-1]

        return mct; 

1178

Title description:
Foreign friends have designed an English version of a word guessing game based on Chinese word puzzles. Please come and guess.
The puzzle of an anagram is given in the form of a string. If a word meets the following two conditions, then it can be counted as the answer: the
word contains the first letter of the puzzle.
Every letter in the word word can be found in the puzzle.
For example, if the face of an anagram is "abcdefg", then the words that can be used as the answer are "faced", "cabbage", and "baggage"; while "beefed" (without the letter "a") and "based" (among them "S" does not appear in the mystery).
Return an answer array answer, each element in the array answer[i] is the number of words corresponding to puzzles[i] in the given word list words.

Example:
Insert picture description here
Answer:

'''
①不用考虑words[i]中重复的字符,以及字符的顺序
换句话说就是 “abbbbcd” 与 "aaaaadcb"应该有相同的hash值(a, b, c, d)
于是我们可以想到计数器
②对于每个puzzles[i],长度固定为7
于是我们可以在有限的空间内列举出所有puzzles[i]的组合
如: "abcdefg"的所有组合
'a', 'b', 'c', 'd', 'e', 'f' , 'g'
'ab', 'ac', 'ad' ......'abc', 'abd'........'abcdefg'
对于其中某个组合'abcd'来说,它的hash值为(a, b, c, d)可以匹配所有words中hash值为(a, b, c, d)的word, 如"abbbbbcd", ”aaaaaaadcb“ 同理组合'abc'可以匹配所有hash值为(a, b, c)的word
将所有组合可匹配的值加起来,就是我们puzzles[i]对应的answer[i]
③word必须包含puzzle的第一个字母
很简单,修改我们的组合思路
我们把除头字母外的puzzle[ i ]也就是puzzle[ i ][ 1 : ]进行组合,在每个组合结果上加上头字母就可满足
如'abcdefg':
查询的hash值应该为'a' + comb('bcdefg')(<-表示'bcdefg'的所有组合情况)
'''

from collections import Counter
from itertools import combinations

class Solution:
    def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
        counter, ans = Counter(filter(lambda x: len(x) <= 7, map(frozenset, words))), [0]*(len(puzzles))
        for index, puzzle in enumerate(puzzles):
            for comb in list(map(lambda i:combinations(puzzle[1:], i), range(7))):
                ans[index] += sum(counter[frozenset((puzzle[0],)+ele)] for ele in comb)
        return ans

Guess you like

Origin blog.csdn.net/yeqing1997/article/details/114111034