Day11: stack and queue 2
Leetcode 20:Valid Parentheses
Consider 3 invalid conditions: right>left; left>right; unmatched
class Solution:
def isValid(self, s: str) -> bool:
stack = []
# 3 invalid conditions:
for ss in s:
if ss == '(':
stack.append(')')
elif ss == '{':
stack.append('}')
elif ss == '[':
stack.append(']')
# 1. left>right or 2. unmatched
elif not stack or stack[-1]!=ss:
return False
else:
stack.pop()
# right>left
return True if not stack else False
Leetcode 1047: Remove All Adjacent Duplicates In String
- 双指针暴力能过104/106; Time Limit Exceeded ; time complexity O ( n 2 ) O(n^2) O(n2)
class Solution:
def removeDuplicates(self, s: str) -> str:
Flag = True
stack = []
while Flag:
for i in range(len(s)-1):
if s[i]==s[i+1]:
stack.append(s[i]+s[i+1])
break
if not stack: return s
else:
s = s.split(stack.pop())
s = ''.join(s)
- Stack: O ( n ) O(n) O(n)
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = []
for ss in s:
if stack and ss == stack[-1]:
stack.pop()
else:
stack.append(ss)
return ''.join(stack)
Leetcode 150: Evaluate Reverse Polish Notation
好难
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for item in tokens:
if item not in {"+", "-", "*", "/"}:
stack.append(item)
else:
first_num, second_num = stack.pop(), stack.pop()
stack.append(
int(eval(f'{second_num} {item} {first_num}')) # 第一个出来的在运算符后面
)
return int(stack.pop())