Python 刷栈 leetcode简单题有感

特殊的单调栈问题,尤其要清晰明白题目需要的是递增栈还是递减栈,以下标入栈容易理解,栈的出栈条件要搞清楚,出栈的下标也要利用

下一个更大元素 I,

class Solution(object):
    def nextGreaterElement(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        n2 = len(nums2)
        ans1 = [-1]*n2
        stack = []
        for i in range(n2):
            while stack and nums2[i] > nums2[stack[-1]]:
                g = stack.pop()
                ans1[g] = nums2[i]
            stack.append(i)
        dt = dict()
        for i in range(n2):
            dt[nums2[i]] = ans1[i]
        ans2 = []
        for i in nums1:
            ans2.append(dt[i])
        return ans2

商品折扣后的最终价格

class Solution(object):
    def finalPrices(self, prices):
        """
        :type prices: List[int]
        :rtype: List[int]
        """
        n = len(prices)
        stack = []
        res = prices
        for j in range(n):

            while stack and prices[j] <= prices[stack[-1]]  :
                i = stack.pop()
                res[i] = prices[i] - prices[j]
            stack.append(j)
            
        
        return res

普通栈问题

删除字符串中的所有相邻重复项

class Solution(object):
    def removeDuplicates(self, s):
        """
        :type s: str
        :rtype: str
        """
        stack = []
        for i in s:
            if stack and stack[-1] == i:
                stack.pop()
            else:
                stack.append(i)
        return .join(i for i in stack)
经验分享 程序员 微信小程序 职场和发展