栈:
先进后出
- 浏览器的后退功能
时间复杂度
- 访问Access — O(1) — 栈顶元素
- 搜索Search — O(N)
- 插入Insert — O(1)
- 删除Delete — O(1) — 栈顶元素
常用操作
-
创建栈
stack = []
– -
添加元素
stack.append()
(添加的元素)
O(1)
– -
获取栈顶元素 — 即将出栈的元素
stack[-1]
– -
删除栈顶元素 — 即将出栈的元素
temp = stack.pop()
O(1)
– -
栈的长度
len(stack)
O(1)
– -
栈是否为空
len(stack) == 0
O(1)
– -
遍历栈 — 边删除栈顶元素边遍历
while len(stack) > 0:
temp = queue.pop()
print(temp)
O(N)
练习题
- 20 . 有效的括号
class Solution:
# Stack
# N is the size of s
# Time Complexity: O(N)
# Space Complexity: O(N)
def isValid(self, s: str) -> bool:
if len(s) == 0:
return Ture
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:
# Stack
# M is the size of num1, N is the size of nums2
# Time Complexity: O(MN)
# Space Complexity: O(N)
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = []
stack = []
for num in nums2:
stack.append(num)
for num in nums1:
temp = []
isFound = False
nextMax = -1
while (len(stack) != 0 and not isFound):
top = stack.pop()
if top > num:
nextMax = top
elif top == num:
isFound = True
temp.append(top)
res.append(nextMax)
while len(temp) != 0:
stack.append(temp.pop())
return res
学习视频来源B站—爱学习的饲养员—手把手带你刷Leetcode力扣