# 20.有效的括号
- 链接:代码随想录
- 重点:左括号必须以正确的顺序闭合。这说明括号一定是({}),而不是({)}。最后一个左括号是{,最先的一个右括号一定是}
- 代码:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) % 2 != 0:
return False
stack = []
for i in s:
if i == "(":
stack.append(")")
elif i == "[":
stack.append("]")
elif i == "{":
stack.append("}")
elif not stack or stack[-1] != i:
return False
else:
stack.pop()
if not stack: # stack is empty
return True
else:
return False
# 1047. 删除字符串中的所有相邻重复项
- 链接:代码随想录
- 第一想法:
class Solution(object):
def removeDuplicates(self, s):
"""
:type s: str
:rtype: str
"""
stack = []
for i in s:
if i not in stack:
stack.append(i)
elif i == stack[-1]:
stack.pop()
return ''.join(stack)
忽略了stack 空了的情况
- 看完代码随想录的想法:
class Solution(object):
def removeDuplicates(self, s):
"""
:type s: str
:rtype: str
"""
stack = []
for i in s:
if stack and i == stack[-1]:
stack.pop()
else:
stack.append(i)
return ''.join(stack)
# 150.逆波兰表达式求值
- 链接:代码随想录
- 第一想法:
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
char = ["+","-","*,""/"]
for i in tokens:
if i == "+":
tmp1 = stack.pop()
tmp2 = stack.pop()
stack.append(tmp2+tmp1)
elif i == "-":
tmp1 = stack.pop()
tmp2 = stack.pop()
stack.append(tmp2-tmp1)
elif i == "*":
tmp1 = stack.pop()
tmp2 = stack.pop()
stack.append(tmp2*tmp1)
elif i == "/":
tmp1 = stack.pop()
tmp2 = stack.pop()
stack.append(tmp2/tmp1)
else:
stack.append(int(i))
print(stack)
return stack[0]
最后一个实例没有过,但是没想出来哪儿有错
- 看完代码随想录的想法:
我的代码在python3的实例就能过,但是超出输出限制
from operator import add, sub, mul
class Solution:
op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)}
def evalRPN(self, tokens):
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()
知道了operator这个包