目录
今日任务:
- 20.有效的括号
- 1047.删除字符串中的所有相邻重复项
- 150.逆波兰表达式求值
20.有效的括号
分析:
- 括号匹配是使用栈解决的经典问题
str.replace()
class Solution:
def isValid(self, s: str) -> bool:
while '{}' in s or '[]' in s or '()' in s:
s = s.replace('{}', '')
s = s.replace('[]', '')
s = s.replace('()', '')
return s == ''
栈:
class Solution:
def isValid(self, s: str) -> bool:
dict_1 = {')':'(', ']':'[', '}':'{'}
stack = []
for i in s:
if stack and i in dict_1:
if stack[-1] == dict_1[i]:
stack.pop()
else:
return False
else:
stack.append(i)
return not stack
1047.删除字符串中的所有相邻重复项
题目链接:1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
分析:
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = []
for i in s:
if stack and stack[-1] == i:
stack.pop()
else:
stack.append(i)
return "".join(stack)
150.逆波兰表达式求值
题目链接:150. 逆波兰表达式求值 - 力扣(LeetCode)
分析:
- python中没有一个函数可以判断一个字符串是否为合理的整数(包括正、负数)。str.isdigit()可以判断正数,但是无法判断负数。
#解决方案:使用int(),并做try-except try: stack.append(int(token)) except: pass
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
try:
stack.append(int(token))
except:
num2 = stack.pop()
num1 = stack.pop()
stack.append(self.evaluate(num1, num2, token))
return stack[0]
def evaluate(self, num1, num2, op):
if op == '+':
return num1 + num2
elif op == '-':
return num1 - num2
elif op == '*':
return num1 * num2
else:
return int(num1 / float(num2))