您的位置:首页 > 其它

Basic Calculator

2015-08-22 21:00 253 查看
题目:

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open
(
and closing parentheses
)
,
the plus
+
or minus sign
-
, non-negative integers
and empty spaces
.

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23


Note: Do not use the
eval
built-in
library function.
解题思路:
是关于中缀表达式的计算,需要用到栈。思路比较简单,用两个栈,一个存储操作数,一个存储操作符。根据每个操作符的优先次序赋予相应的权值。不断进行入栈操作,直到得出结果。代码如下:

class Solution(object):

def calculate(self, s):

"""

:type s: str

:rtype: int

"""

def cal(num1,num2,op):

if op=='+':

return num1+num2

elif op=='-':

return num1-num2

def readNum(s,index):

res = 0

while s[index] in '0123456789':

res = 10*res+int(s[index])

index = index+1

return res,index

map = {'$':0, '(':1, ')':1, '+':2, '-':2}

operator, operand = ['$'], []

s = ''.join((s+'$').split())

index = 0

while len(operator)!=0:

i = s[index]

if i not in '()+-$':

num ,index= readNum(s,index)

operand.append(num)

else:

if i=='$' and operator[len(operator)-1]=='$':

return operand.pop()

elif i==')' and operator[len(operator)-1]=='(':

operator.pop()

index += 1

elif i=='(' or map[i]>map[operator[len(operator)-1]]:

operator.append(i)

index += 1

else:

num1,num2 = operand.pop(), operand.pop()

num = cal(num2,num1,operator.pop())

operand.append(num)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: