一、栈(Stack)
访问 Access :O(1) 栈顶元素
搜索 Search :O(N)
插入 Insert :O(1)
删除 Remove :O(1) 栈顶元素
二、Python 栈的常用操作:
1、创建栈
2、添加元素
3、获取栈顶元素
4、删除栈顶元素
5、 栈的大小
6、栈是否为空
7、栈的遍历(边删除边遍历)
三、力扣20题
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0:
return True
stack = []
for c in s:
if c == '(' or c == '[' or c == '{':
stack.append(c)
else:
if len(stack) == 0:
return False
else:
temp = stack.pop()
if c == ')':
if temp != '(':
return False
elif c == ']':
if temp != '[':
return False
elif c == '}':
if temp != '{':
return False
return True if len(stack) == 0 else False
四、力扣496题
class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res = []
stack = []
for num in nums2:
stack.append(num)
for num in nums1:
temp = []
isFound = False
max = -1
while(len(stack) != 0 and not isFound):
top = stack.pop()
if top > num:
max = top
elif top == num:
isFound = True
temp.append(top)
res.append(max)
while len(temp) != 0:
stack.append(temp.pop())
return res