文档参考:programmercarl.com
今天的题也挺友善的,栈应该算比较轻松的吧
20.有效的括号
"""
简单易懂,左边入栈,右边靠出栈匹配
"""
class Solution(object):
def isValid(self, s):
stack = []
left = ['(', '[', '{'] # 需要入栈的符号
for i in s:
if i in left:
stack.append(i) # 满足left数组就可以入栈
else:
if stack == []: # 如果栈为空,说明此时肯定为非法字符串
return False
temp = stack.pop() # 弹出最近添加入栈的元素进行匹配
if i == ')' and temp == '(':
continue
elif i == ']' and temp == '[':
continue
elif i == '}' and temp == '{':
continue
else:
return False
# 全部匹配完之后就判断栈内是否还有元素
if stack == []:
return True
else:
return False
1047.删除字符串中的所有相邻重复的字母
"""
用栈进行,只能说是术业有专攻
"""
class Solution(object):
def removeDuplicates(self, s):
stack = [] # 设置栈
for i in s:
if stack == []: # 如果栈为空,则将新字符i添加到栈中
stack.append(i)
else: # 否则pop出最新添加进来的字符,并进行消消乐
temp = stack.pop()
if temp == i: # 相同就接着进行匹配
continue
else: # 不同就先将刚才pop出去的最新字符添加回来,以及不匹配的新字符i也要添加进栈
stack.append(temp)
stack.append(i)
return ''.join(stack)
150.逆波兰表达式
class Solution(object):
def evalRPN(self, tokens):
stack = []
signs = ['+', '-', '*', '/']
for item in tokens:
if item not in signs: # 判断此时加入的是否为符号
stack.append(item)
else: # 如果是符号,则取出栈中的前两位数,并计算结果
num_1 = stack.pop()
num_2 = stack.pop()
res = eval(f'{int(num_2)}{item}{int(num_1)}')
stack.append(int(res))
return stack.pop()
今天比较晚,题也算简单,就这样吧,栈甚至不用看源代码就能写出来(