Basic Calculator

来源:互联网 发布:淘宝公益宝贝什么意思 编辑:程序博客网 时间:2024/05/17 06:08

题目:

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)

0 0