# leetcode之Basic Calculator

class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
import re
listofnum = []
listofsym = []
symbol = ['(', ')', '+', '-']
#空集
if len(s) == 0:
return 0
#一个字母
try:
return int(s)
except:
#将所有项分别列出来
s = re.sub(' ', '', s)
n = ''
for i in range(len(s)):
try:
if s[i] in symbol:
listofnum.append(int(n))
listofsym.append(s[i])
n = ''
elif i == len(s) - 1:
n = n + s[i]
listofnum.append(int(n))
else:
n = n + s[i]
except:
listofsym.append(s[i])
#计算括号
if s[i] == ')':
listofsym.pop()
while listofsym[-1] != '(':
a = listofnum.pop()
b = listofnum.pop()
if listofsym[-1] == '-':
if listofsym[-2] == '-':
listofnum.append(a + b)
else:
listofnum.append(b - a)
else:
if listofsym[-2] == '-':
listofnum.append(b - a)
else:
listofnum.append(b + a)
listofsym.pop()
listofsym.pop()
#计算括号之外的
while len(listofsym) != 0:
a = listofnum.pop()
b = listofnum.pop()
try:
if listofsym[-1] == '-':
if listofsym[-2] == '-':
listofnum.append(a + b)
else:
listofnum.append(b - a)
else:
if listofsym[-2] == '-':
listofnum.append(b - a)
else:
listofnum.append(b + a)
listofsym.pop()
except:
if listofsym[-1] == '-':
return b - a
else:
return a + b
return listofnum[0]

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode之Basic Calculator 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)