class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
tokens = ["+", "-", "*", "/"]
token1 = ["+", "-"]
token2 = ["*", "/"]
operators = []
operands = []
res = 0
cur = 0
for x in range(len(s)):
if s[x] in tokens:
operators.append(int(s[cur:x]))
if len(operators) < 2:
operands.append(s[x])
else:
if operands[-1] in token2:
tmp = cal(operands[-1], operators[-2], operators[-1])
operators = operators[:-2]
operators.append(tmp)
operands = operands[:-1]
elif operands[-1] in token1 and s[x] in token1:
tmp = cal(operands[0], int(operators[0]), int(operators[1]))
operators = operators[1:]
operators[0] = tmp
operands = operands[1:]
operands.append(s[x])
cur = x+1
if x == len(s) - 1:
operators.append(int(s[cur:]))
if len(operands) != 0 and operands[-1] in token2:
tmp = cal(operands[-1], int(operators[-2]), int(operators[-1]))
operators = operators[:-2]
operators.append(tmp)
operands = operands[:-1]
while len(operands) != 0 or len(operators) != 0:
if len(operators) == 1 and len(operands) == 0:
return operators[0]
tmp = cal(operands[0], int(operators[0]), int(operators[1]))
operators = [tmp] + operators[2:]
operands = operands[1:]
def cal(operand, operator1, operator2):
if operand == "+":
return operator1 + operator2
if operand == "-":
return operator1 - operator2
if operand == "*":
return operator1 * operator2
if operand == "/":
return operator1 / operator2