0223leetcode brushes 5 python questions

125

Title description:
Given a string, verify whether it is a palindrome. Only letters and numbers are considered, and the capitalization of letters can be ignored.
Explanation: In this question, we define an empty string as a valid palindrome string.

Example:
Insert picture description here
Answer:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        '''
        #filter函数,过滤字符串 isalnum保留数字字母
        s=''.join(filter(str.isalnum,s)).lower()
        return s==s[::-1]
        '''
        #正则
        s=re.sub('[^a-zA-Z0-9]','',s)
        s=s.lower()
        return s==s[::-1] 

209

Title description;
given an array containing n positive integers and a positive integer target.
Find the continuous sub-array [numsl, numsl+1, …, numsr-1, numsr] with the smallest length satisfying its sum ≥ target in the array, and return its length. If there is no sub-array that meets the criteria, 0 is returned.

Example:
Insert picture description here
Answer:

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        if target>sum(nums):
            return 0
        left,right,res,sum_lr=0,0,len(nums)+1,0
        while right < len(nums):
            while sum_lr<target and right<len(nums):  # sum_lr小则右指针右移
                sum_lr += nums[right]
                right += 1
            while sum_lr>=target and left>=0:  # sum_lr大则左指针右移
                res = min(res, right-left)
                sum_lr -= nums[left]
                left += 1
        return res

1008

Title description:
Return the root node of the binary search tree that matches the given preorder traversal preorder.
(Recall that a binary search tree is a type of binary tree, each node of which satisfies the following rules. For any descendant of node.left, the value is always <node.val, and any descendant of node.right, the value is always> node .val. In addition, the preorder traversal first displays the value of the node node, then traverses node.left, and then traverses node.right.) The
question guarantees that for a given test case, a binary search tree that meets the requirements can always be found.

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 bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        if not preorder:
            return None
        root = TreeNode(preorder[0]) 
        left, right = [], []
        for x in preorder[1:]:
            if x < root.val:
                left.append(x)
            else:
                right.append(x)
            
        root.left = self.bstFromPreorder(left)
        root.right = self.bstFromPreorder(right)
        return root

1052

Topic description:
Today, the bookstore owner has a store that plans to open customers.length minutes. Every minute some customers (customers[i]) will enter the bookstore, and all these customers will leave after that minute is over.
At some point, the bookstore owner will get angry. If the bookstore owner is angry at the i-th minute, then grumpy[i] = 1, otherwise grumpy[i] = 0. When the bookstore owner is angry, the customers will be dissatisfied at that minute, and they will be satisfied if they are not angry.
The bookstore owner knows a secret technique that can restrain his emotions and keep himself from getting angry for X minutes, but he can only use it once.
Please return to this day of business, the maximum number of customers that can be satisfied.

Example:
Insert picture description here
Answer:

class Solution:
    def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
        n=len(grumpy)
        nums1=sum(customers[:X])
        nums2=0
        for i in range(X,n):
            if grumpy[i]==0:
                nums2+=customers[i]
        max_nums = nums1 + nums2
        for i in range(1, n - X + 1):
            nums1 -= customers[i - 1]
            nums1 += customers[i + X - 1]
            if grumpy[i - 1] == 0:
                nums2 += customers[i - 1]
            if grumpy[i + X - 1] == 0:
                nums2 -= customers[i + X - 1]
            max_nums = max(max_nums, nums2 + nums1)
        return max_nums

1750

Title description:
Give you a string s that only contains the characters'a','b' and'c'. You can perform the following operations (5 steps) any number of times:
select the string s as a non-empty prefix, this All characters of the prefix are the same.
Select a non-empty suffix of the string s, all characters of this suffix are the same.
The prefix and suffix must not overlap anywhere in the string.
All characters contained in the prefix and suffix must be the same.
Delete the prefix and suffix at the same time.
Please return the shortest length that can be obtained after performing the above operations on the string s any number of times (maybe 0 times).

Example:
Insert picture description here
Answer:

class Solution:
    def minimumLength(self, s: str) -> int:
        l=0
        r=len(s)-1
        while l<r and s[l]==s[r]:
            while l<r and s[l]==s[l+1]:
                l+=1
            while l<r and s[r]==s[r-1]:
                r-=1
            l+=1
            r-=1
        return max(r-l+1,0)

Guess you like

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