按照CyC2018 (Github star 超过99k, 详情请见https://github.com/CyC2018/CS-Notes/blob/master/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E6%A0%88%E5%92%8C%E9%98%9F%E5%88%97.md)总结的练习【python版】。
废话不多说,上菜~
元素每经过一个栈,出栈的顺序就会被反转,因此连续经过两个栈,就可达到队列先进先出的目的。2
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.A = []
self.B = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.A.append(x)
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
if len(self.B)==0 and len(self.A)==0:
return True
else:
return False
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if self.empty():
return
if len(self.B) == 0:
while len(self.A) != 0:
self.B.append(self.A.pop())
return self.B.pop()
else:
return self.B.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if self.empty():
return
if len(self.B) == 0:
while len(self.A) != 0:
self.B.append(self.A.pop())
return self.B[-1]
else:
return self.B[-1]
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.A = []
self.B = []
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.A.append(x)
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
while len(self.A)>1:
self.B.append(self.A.pop(0))
temp = self.A.pop(0)
self.A, self.B = self.B, self.A
return temp
def top(self) -> int:
"""
Get the top element.
"""
while len(self.A) > 1:
self.B.append(self.A.pop(0))
temp = self.A.pop(0)
self.B.append(temp)
self.A, self.B = self.B, self.A
return temp
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
if len(self.A) == 0:
return True
else:
return False
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
要求实现一个常数时间内能检索到最小值的栈
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min_stack = [math.inf]
def push(self, x: int) -> None:
self.stack.append(x)
self.min_stack.append(min(x, self.min_stack[-1]))
def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
class Solution:
def isValid(self, s: str) -> bool:
dic = {'(':')','{':'}', '[':']'}
mystack = []
for item in s:
if item in ['(', '{', '[']:
mystack.append(item)
if item in [')', '}', ']']:
if not mystack:
return False
tmp = mystack.pop()
if dic[tmp] != item:
return False
if mystack:
return False
return True