255. Verify Preorder Sequence in Binary Search Tree
class Solution(object):
def verifyPreorder(self, preorder):
if not preorder:return True
largerThan = float('-inf')
stack = []
for n in preorder:
if n < largerThan: return False
while stack and n > stack[-1]: # 这里可以改成O(1)space 不需要stack,只要比前一个大就一直往前找就行了
largerThan = stack.pop()
stack.append(n)
return True
1003. Check If Word Is Valid After Substitutions
很简单的题,一遍过。但是又是看了标签是stack的才肯定。
class Solution(object):
def isValid(self, S):
stack = []
for c in S:
stack.append(c)
cur = ''
while stack:
cur = stack.pop() + cur
if len(cur) >= 3 and cur[:3] == 'abc':
cur = cur[3:]
return not cur
402. Remove K Digits
Well, one can simply scan from left to right, and remove the first "peak" digit; the peak digit is larger than its right neighbor. One can repeat this procedure k times, and obtain the first algorithm
class Solution(object):
def removeKdigits(self, num, k):
out = []
for n in num:
while k and out and out[-1] > n:
out.pop()
k -= 1
out.append(n)
return ''.join(out[:-k or None]).lstrip('0') or '0' # -k or None: 如‘9’ 1的情况, 此时k=1 这样返回的才会是0
739. Daily Temperatures
Too simple
class Solution(object):
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
re = [0] * len(T)
stack = [0]
for i in xrange(1, len(T)):
while stack and T[i] > T[stack[-1]]:
ids = stack.pop()
re[ids] = i - ids
else:
stack.append(i)
return re
84. Largest Rectangle in Histogram
https://leetcode.com/articles/largest-rectangle-in-histogram/
class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
stack = []
stack.append(-1)
maxArea = 0
for i in xrange(len(heights)):
while stack[-1] != -1 and heights[i] <= heights[stack[-1]]: # 注意是 <=
maxArea = max(maxArea, (i-stack[-2]-1)*heights[stack[-1]])
stack.pop()
stack.append(i)
# while stack[-1] != -1:
# maxArea = max(maxArea, (stack[-1] - stack[-2]) * heights[stack[-1]])
# stack.pop()
right = stack[-1] # 上面的是错的, right_index应该一直是最后一个
while stack[-1] != -1:
maxArea = max(maxArea, (right - stack[-2]) * heights[stack[-1]])
stack.pop()
return maxArea
503. Next Greater Element II
https://leetcode.com/articles/next-greater-element-ii/
class Solution(object):
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = [0] * len(nums)
stack = []
for i in xrange(len(nums)*2-1, -1, -1):
ids = i % len(nums)
# 一直pop到比它大的,放入结果中
while stack and nums[stack[-1]] <= nums[ids]:
stack.pop()
res[ids] = -1 if not stack else nums[stack[-1]]
stack.append(ids)
return res
394. Decode String
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string]
, where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a
or 2[4]
.
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack = [["", 1]]
num = ""
for ch in s:
if ch.isdigit():
num += ch
elif ch == '[':
stack.append(['', int(num)])
num = ''
elif ch == ']':
stri, k = stack.pop()
stack[-1][0] += stri*k
else:
stack[-1][0] += ch
return stack[0][0]
173. Binary Search Tree Iterator
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next()
will return the next smallest number in the BST.
Note: next()
and hasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
# Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.push(root)
def hasNext(self):
"""
:rtype: bool
"""
return self.stack
def next(self):
"""
:rtype: int
"""
tempNode = self.stack.pop()
self.push(tempNode.right)
return tempNode.val
def push(self, node):
while node:
self.stack.append(node)
node = node.left
636. Exclusive Time of Functions
["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"]
class Solution(object):
def exclusiveTime(self, n, logs):
"""
:type n: int
:type logs: List[str]
:rtype: List[int]
"""
re = [0] * n
stack = []
for log in logs:
fid, state, time = log.split(':')
time = int(time)
if state == 'start':
stack.append([time, 0])
else:
start_time, middle_time = stack.pop()
re[int(fid)] += time - start_time + 1 - middle_time
if stack: # middle time
stack[-1][1] += time - start_time + 1
return re
155. Min Stack
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
if not self.stack:
curMin = x
else:
curMin = x if x < self.stack[-1][1] else self.stack[-1][1]
self.stack.append((x, curMin))
def pop(self):
"""
:rtype: void
"""
val, curMin = self.stack.pop()
return val
def top(self):
"""
:rtype: int
"""
return self.stack[-1][0]
def getMin(self):
"""
:rtype: int
"""
return self.stack[-1][1]