20. 有效的括号
题目描述: 20. 有效的括号.
解法
class Solution(object):
def isValid(self, s):
stack = []
d = {
'{':'}',
'(':')',
'[':']'
}
for i in s:
if i in ["{","[","("]:
stack.append(i)
else:
if not stack:
return False
c = stack.pop()
if d[c] != i:
return False
return not stack
栈的经典应用。
1047. 删除字符串中的所有相邻重复项
题目描述: 1047. 删除字符串中的所有相邻重复项.
解法
class Solution(object):
def removeDuplicates(self, s):
stack = []
for c in s:
if not stack or stack[-1] != c:
stack.append(c)
else:
stack.pop()
return ''.join(stack)
也是经典问题了
150. 逆波兰表达式求值
题目描述: 150. 逆波兰表达式求值.
解法
class Solution(object):
def evalRPN(self, tokens):
stack = []
for token in tokens:
if token not in ['+','-','*','/']:
stack.append(token)
else:
if token == '+':
stack.append(int(stack.pop()) + int(stack.pop()))
elif token == '*':
stack.append(int(stack.pop()) * int(stack.pop()))
elif token == '-':
b = int(stack.pop())
a = int(stack.pop())
stack.append(a-b)
else:
b = int(stack.pop())
a = int(stack.pop())
stack.append(int(a/b))
return int(stack[0])
"""
:type tokens: List[str]
:rtype: int
"""
注意整除用//,向0取整用int(a/b)