栈与队列20|1047|150
20有效的括号
class Solution: def isValid(self, s: str) -> bool: s_list = list(s) if len(s_list) % 2 != 0: return False stack = [] for item in s_list: if item == "(": stack.append(")") elif item == "[": stack.append("]") elif item == "{": stack.append("}") elif item == ")" or item == "]" or item == "}": if len(stack) == 0 or stack[-1] != item: return False elif stack[-1] == item: stack.pop() if len(stack) == 0: return True elif len(stack) != 0: return False
1047删除字符串中的所有相邻重复项
class Solution: def removeDuplicates(self, s: str) -> str: stack = [] s_list = list(s) result = "" for item in s_list: if len(stack) == 0 or stack[-1] != item: stack.append(item) elif stack[-1] == item: stack.pop() for item in stack: result += item return result
150逆波兰表达式求值
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for item in tokens: if item in {"+", "-", "*", "/"}: num2 = stack.pop() num1 = stack.pop() if item == "+": val = num1 + num2 elif item == "-": val = num1 - num2 elif item == "*": val = num1 * num2 elif item == "/": val = num1 // num2 if val < 0 and num1 % num2 != 0: val += 1 stack.append(val) else: stack.append(int(item)) return stack.pop()