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()