20. Valid Parentheses
use stack to add every left parenthesis and add the right counterpart into a stack. if the next element is not left and equals to the last element in the stack (in this case, the element is a right parenthesis) the last element is poped. Iterate through, all added elements will be poped if the string is valid. Not only the numbers need to match but also the order.
class Solution:
def isValid(self, s: str) -> bool:
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. Remove All Adjacent Duplicates In String
append every element into a stack. if the next element == the last element in the stack, pop the last element in the stack.
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = []
for i in s:
if len(stack) > 0:
if stack[-1] == i:
stack.pop()
continue
stack.append(i)
return ''.join(stack)
150. Evaluate Reverse Polish Notation
To solve this question, append a number into the stack. when having an operator. pop the last two elements in the stack and do the operation on it.
class Solution:
op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)}
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for i in tokens:
if i not in ['+', '-', '*', '/']:
stack.append(int(i))
else:
second = stack.pop()
first = stack.pop()
new_num = self.op_map[i](first,second)
stack.append(new_num)
return stack.pop()
文章介绍了使用栈解决三个问题:验证括号的有效性,移除字符串中相邻的重复字符,以及评估逆波兰表示法。在括号验证中,遇到左括号就压入栈,遇到右括号时检查是否匹配;在移除重复字符时,如果连续字符相同则从栈中移除;对于逆波兰表达式,栈用于存储数字,遇到运算符时取出栈顶两个数字进行计算并回压结果。
2580

被折叠的 条评论
为什么被折叠?



