20. 有效的括号
解法1:用字典形式
class Solution:
def isValid(self, s: str) -> bool:
# method 1
stack = []
dic = {')':'(','}':'{',']':'['}
for sy in s:
if sy in dic:
if not stack or stack[-1] != dic[sy]:
return False
else:
stack.pop()
else:
stack.append(sy)
return not stack
解法2:栈形式
class Solution:
def isValid(self, s: str) -> bool:
# method 2
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()
return not stack
1047. 删除字符串中的所有相邻重复项
解法1:栈
class Solution:
def removeDuplicates(self, s: str) -> str:
res = []
for i in s:
if res and i == res[-1]:
res.pop()
else:
res.append(i)
return ''.join(res)
150. 逆波兰表达式求值
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
res = []
operator = ['+','-','*','/']
for i in tokens:
if i not in operator:
res.append(i)
else:
first = res.pop()
second = res.pop()
res.append(int(eval(f'{first}{i}{second}')))
return res.pop()