20. Valid Parentheses
3种情况:
1.左括号多了
2.右括号多了
3.左右括号不匹配例如}{
技巧:
1.遇到左括号存对应的右括号。方便比较。
2.遇到空,就return。
3.剪枝:奇数一定不符合匹配原则。可以直接return
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for item in s:
if item == '(':
stack.append(')')
elif item == '[':
stack.append(']')
elif item == '{':
stack.append('}')
elif not stack or stack[-1] != item: #第三和第二种情况,且两个判断不能调转(空指针异常)
return False
else:
stack.pop()
return True if not stack else False #第一种情况
要知道栈为什么适合做这种类似于爱消除的操作,因为栈帮助我们记录了 遍历数组当前元素时候,前一个元素是什么
stack:擅长相邻字符的消除操作
1047. Remove All Adjacent Duplicates In String
class Solution(object):
def removeDuplicates(self, s):
"""
:type s: str
:rtype: str
"""
stack = []
for x in s:
if stack and stack[-1]==x:
stack.pop()
else:
stack.append(x)
return "".join(stack)
放入stack,一遇相同元素就pop -> 相邻字符的消除
150. Evaluate Reverse Polish Notation
classic problem using stack
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
op = ['+','-','*','/']
for t in tokens:
if t in op:
x = int(stack.pop())
y = int(stack.pop())
stack.append(x+y if t == '+' else y-x if t == '-' else x*y if t =='*' else int(y/x))
else:
stack.append(t)
return int(stack[-1])