# 实现一个基本的计算器来计算一个简单的字符串表达式的值。
# 字符串表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。
#
# 示例 1:
# 输入: "3+2*2"
# 输出: 7
#
# 示例 2:
# 输入: " 3/2 "
# 输出: 1
#
# 示例 3:
# 输入: " 3+5 / 2 "
# 输出: 5
#
# 说明:
# 你可以假设所给定的表达式都是有效的。
# 请不要使用内置的库函数 eval。
# python中的strip()可以去除头尾指定字符
# 想要去除中间字符,可以使用replace()函数
class Solution:
def calculate(self, s: str) -> int:
s = s.replace(' ', '')
lens = len(s)
test_stack = []
index1 = 0
index2 = 0
while index2 != lens:
if s[index2] == '+' or s[index2] == '-' or s[index2] == '*' or s[index2] == '/':
test_stack.append(int(s[index1:index2]))
test_stack.append(s[index2])
index2 += 1
index1 = index2
else:
index2 += 1
test_stack.append(int(s[index1:index2]))
# 遍历完成
# 换栈
test_stack2 = []
lens2 = len(test_stack)
for j in range(lens2):
test_stack2.append(test_stack.pop())
while test_stack2 != []:
key = test_stack2.pop()
if key != '*' and key != '/':
test_stack.append(key)
elif key == '*':
pre = test_stack.pop()
test_stack.append(pre * test_stack2.pop())
elif key == '/':
pre = test_stack.pop()
test_stack.append(pre // test_stack2.pop())
lens3 = len(test_stack)
for f in range(lens3):
test_stack2.append(test_stack.pop())
result = test_stack2.pop()
while test_stack2 != []:
key = test_stack2.pop()
if key == '+':
result += test_stack2.pop()
elif key == '-':
result -= test_stack2.pop()
return result