20. 有效的括号
class Solution:
def isValid(self, s: str) -> bool:
stk = []
upper = ["(", "{", "["]
lower = [")", "}", "]"]
dictionary = {")":"(", "}":"{", "]":"["}
for i in range(len(s)):
if s[i] in upper:
stk.append(s[i])
elif s[i] in lower:
if not stk or dictionary[s[i]] != stk[-1]:
return False
else:
stk.pop()
if stk:
return False
else:
return True
1047. 删除字符串中的所有相邻重复项
class Solution:
def removeDuplicates(self, s: str) -> str:
stk = []
for i in range(len(s)):
if not stk:
stk.append(s[i])
elif stk[-1] == s[i]:
stk.pop()
else:
stk.append(s[i])
return ''.join(stk)
150. 逆波兰表达式求值
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stk = []
operator = ['+', '-', '*', '/']
for i in tokens:
if i in operator and stk:
temp_later = int(stk.pop())
if not stk:
return 0
temp_former = int(stk.pop())
if i == '+':
temp_result = temp_former + temp_later
elif i == '-':
temp_result = temp_former - temp_later
elif i == '*':
temp_result = temp_former * temp_later
elif i == '/':
temp_result = temp_former / temp_later
stk.append(temp_result)
else:
stk.append(i)
return int(stk[0])
标签:150,elif,return,temp,随想录,stk,result,求值,former
From: https://www.cnblogs.com/miramira/p/18107438