20. Valid Parentheses(有效的括号)
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
stacks are first-in-last-out. must first come in the mind
meet a '(' append a ')',meet a '[' append a ']'...... meet a ')' and if stack[-1] == item then stack.pop() . make sure there is no item in the stack .
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: #wrong: elif stack is None
return False
else:
stack.pop()
return True if not stack else False
1047. Remove All Adjacent Duplicates In String (相邻的重复项)
You are given a string s
consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s
until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
Why Stack?
why stacks are good for this Eliminator-like(消除) operation is that they help us keep track of what the previous element was ,,,when we traverse the current element of the array.
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = []
for item in s:
if not stack or stack[-1] != item: # wrong : stack.pop() != item 这样if里面就提前pop()掉了
stack.append(item)
else:
stack.pop()
return ''.join(stack)
150. Evaluate Reverse Polish Notation (求 逆 波兰 表达式)
You are given an array of strings tokens
that represents an arithmetic expression(算数表达式) in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
- The valid operators are
'+'
,'-'
,'*'
, and'/'
. - Each operand(运算对象) may be an integer or another expression.
- The division between two integers always truncates toward zero(截尾到0/保留整数).
- There will not be any division by zero.
- The input represents a valid arithmetic expression in a reverse polish notation.
- The answer and all the intermediate calculations can be represented in a 32-bit integer.
wrong solution:?
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for item in tokens:
if item not in {"+", "-", "*", "/"}:#wrong: if item != "+" or "-" or "*" or "/":
stack.append(int(item))# wrong: stack.append(item)
else:
if item == "+":
stack.append(stack.pop() + stack.pop())
elif item == "-":
stack.append(-(stack.pop() - stack.pop()))
elif item == "*":
stack.append(stack.pop() * stack.pop())
elif item == "/":
stack.append(1//(stack.pop()/stack.pop()))
return int(stack.pop())#wrong: stack.pop()
Needs modification:
stack.append(int(1/(stack.pop()/stack.pop())))
or use:
b = stack.pop()
a = stack.pop()
stack.append(int(a / b)) # wrong: stack.append(a//b)
attention different between int(a/b) and a//b:
difference1:
int rounds towards zero , //(floor division" or "integer division) rounds towards smaller.
int(-0.4) = 0
4 // -10 =-1
difference2:
from operator import add, sub, mul
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()