一、 有效的括号
if stack:
表示的是非空
if not stack :
表示空
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for i in s:
if i == '(':
stack.append(')')
elif i == '[':
stack.append(']')
elif i == '{':
stack.append('}') # 把(,[,{ 对应的右括号 加入stack
elif not stack :
# 如果stack为空 此时 有i 但stack为空 对应第三种情况
return False
elif stack and stack[-1] != i:
# 当前括号不等于stack最后一个元素 且stack不为空 对应第二种情况
return False
else : # stack不为空,相等
stack.pop()
return True if not stack else False # 遍历完s后,stack为空则是 True
#elif not stack :
#return False
#elif stack and stack[-1] != i:
#return False
# 可以写成 elif not stack or stack[-1] != i:
# return False
二、 删除字符串中的所有相邻重复项
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = []
for i in s:
if stack and i==stack[-1] :# 如果stack不为空 并且当前元素等于stack的最后一个元素
stack.pop()
else : # 为空 或者 不等于
stack.append(i)
return ''.join(stack)
三、 逆波兰表达式求值
需要弄懂它的计算规则
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for i in tokens:
# 没有运算符时,把数往stack中加
if i not in ('+','-','*','/'):
stack.append(i)
# 碰到运算符,删除并记录stack最后的两个数进行运算
if i == '+':
num1 = stack.pop()
num2 = stack.pop()
# 运算后把结果再加到stack中
stack.append(int(num2)+int(num1))
if i == '-':
num1 = stack.pop()
num2 = stack.pop()
stack.append(int(num2)-int(num1))
if i == '*':
num1 = stack.pop()
num2 = stack.pop()
stack.append(int(num2)*int(num1))
if i == '/':
num1 = stack.pop()
num2 = stack.pop()
stack.append(int(num2)/int(num1))
return int(stack.pop())
进阶版
把运算符做成字典
from operator import add, sub, mul
class Solution:
op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)}
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token not in {'+', '-', '*', '/'}:
stack.append(int(token))
else:
op2 = stack.pop()
op1 = stack.pop()
stack.append(self.op_map[token](op1, op2)) # 第一个出来的在运算符后面
return stack.pop()