classSolution(object): defnextGreaterElement(self, findNums, nums): """ :type findNums: List[int] :type nums: List[int] :rtype: List[int] """ res = [] stack = [] # to store dic = dict() for i in range(len(nums)): while stack and nums[i] > stack[-1]: dic[stack.pop()] = nums[i] stack.append(nums[i]) # deal with last while stack: dic[stack.pop()] = -1 for i in range(len(findNums)): res.append(dic[findNums[i]]) return res
739. Daily Temperatures
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): defdailyTemperatures(self, temperatures): """ :type temperatures: List[int] :rtype: List[int] """ res = [0] * len(temperatures) stack = [] left = 0 for i in range(len(temperatures)): while stack and temperatures[i] > temperatures[stack[-1]]: index = stack.pop() res[index] = i - index stack.append(i) return res
503. Next Greater Element II
1 2 3 4 5 6 7 8 9 10
classSolution(object): # stack defnextGreaterElements(self, nums): stack, res = [], [-1] * len(nums) for i in range(len(nums)) * 2: while stack and (nums[stack[-1]] < nums[i]): res[stack.pop()] = nums[i] stack.append(i) return res
classSolution(object): defremoveDuplicateLetters(self, s): """ :type s: str :rtype: str """ stack = [] dic = dict() for char in s: dic[char] = dic.get(char, 0) + 1 for char in s: dic[char] -= 1 if char in stack: continue else: while stack and ord(char) < ord(stack[-1]) and dic[stack[-1]] > 0: stack.pop() stack.append(char) return"".join(stack)
稍难题
84. Largest Rectangle in Histogram
维持一个递增stack,碰到一个比栈顶元素小的数,不断比较,更新最大面积
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): deflargestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ res = 0 stack = [] for i in range(len(heights)+1): height = heights[i] if i!= len(heights) else0 while stack and height <= heights[stack[-1]]: h = heights[stack.pop()] w = i - stack[-1] -1if stack else i res = max(res, h*w) stack.append(i) return res
classSolution(object): defmaximalRectangle(self, matrix): # O(m^2) ifnot matrix ornot matrix[0]: return0 n = len(matrix[0]) # init heights array height = [0] * (n + 1) ans = 0 # calculate each row for row in matrix: for i in range(n): # count next level '1' height[i] = height[i] + 1if row[i] == '1'else0 stack = [] for i in range(n + 1): while stack and height[i] <= height[stack[-1]]: h = height[stack.pop()] # if not stack means left boundary is zero then width is i else is the stack[-1] index w = i - 1 - stack[-1] if stack else i ans = max(ans, h * w) stack.append(i) return ans