classSolution:defisValid1(self, s:str)->bool:
stack =[]for v in s:if v =='('or v =='{'or v =='[':
stack.append(v)else:ifnot stack:returnFalseif v ==')'and stack[-1]=='(':
stack.pop()elif v =='}'and stack[-1]=='{':
stack.pop()elif v ==']'and stack[-1]=='[':
stack.pop()else:returnFalsereturnnot stack
defisValid(self, s:str)->bool:# 这种简洁一点写法
stack =[]for v in s:if v =='(':
stack.append(')')elif v =='[':
stack.append("]")elif v =='{':
stack.append("}")elifnot stack or stack[-1]!= v:returnFalseelse:# 相等弹出元素
stack.pop()returnTrueifnot stack elseFalse
classSolution:defremoveDuplicates(self, s:str)->str:
res =[]for value in s:if res and value == res[-1]:
res.pop()continueelse:
res.append(value)return"".join(res)
classSolution:defevalRPN(self, tokens: List[str])->int:#
stack =[]for v in tokens:if v =='+':
temp_1 =int(stack.pop())
temp_2 =int(stack.pop())
stack.append(temp_1 + temp_2)elif v =='-':
temp_1 =int(stack.pop())
temp_2 =int(stack.pop())
stack.append(temp_2 - temp_1)elif v =='*':
temp_1 =int(stack.pop())
temp_2 =int(stack.pop())
stack.append(temp_1 * temp_2)elif v =='/':
temp_1 =int(stack.pop())
temp_2 =int(stack.pop())
stack.append(temp_2 / temp_1)else:
stack.append(v)returnint(stack.pop())classSolution:'''
Push the operands to a stack.
When reached an operator,
pop two operands from the stack,
perform the operation,
and push the result back to the stack.
Time complexity: O(n). Space complexity: O(n).
'''defevalRPN(self, tokens: List[str])->int:
s =[]for token in tokens:if token in'+-*/':
op1, op2 = s.pop(), s.pop()if token =='+':
s.append(op2 + op1)elif token =='-':
s.append(op2 - op1)elif token =='*':
s.append(op2 * op1)else:
s.append(int(op2 / op1))# truncate towards zeroelse:
s.append(int(token))return s[0]