今天的三道题目都是栈的应用,涉及到匹配的问题
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 len(stack)==0
##使用字典
def isValid1(self, s: str) -> bool:
if not s :return True
mapping = {')':'(','}':'{',']':'['}
stack = []
for i in s:
if i in mapping.values():
stack.append(i)
elif i in mapping:
if not stack or mapping[i] != stack[-1]:
return False
else : stack.pop()
return len(stack) == 0
字典的判断:分别针对字典中的key和value
if i in mapping = if i in mapping.key()
if i in mapping.values()
类似括号匹配问题,只是最后输出的格式需要注意,输出一个字符串而不是一个栈
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = []
for i in s:
if not stack:
stack.append(i)
elif i!= stack[-1]:
stack.append(i)
elif i== stack[-1]:
stack.pop()
return ''.join(stack)
逆波兰表达式:后缀表达式
输入:tokens = ["2","1","+","3","*"] 输出:9 解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token not in {'+', '-', '*', '/'}:
stack.append(int(token))
else:
pop1 = stack.pop()
pop2 = stack.pop()
if token == '+':
stack.append(pop1+pop2)
elif token == '-':
stack.append(pop2-pop1)
elif token == '*':
stack.append(pop2*pop1)
elif token == '/':
stack.append(int(pop2/pop1))
return stack.pop()
也是利用栈的思路,只不过不是匹配成功出栈,而是匹配到(遍历过程中遇到运算符号),将栈的最后两个数字出栈进行运算再入栈
此处需注意出栈的顺序pop1和pop2,运算过程永远是后出栈的元素和先出栈的元素进行运算