leetcode224. 基本计算器

def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        s = "(" + s.replace(" ","")
        s = s.replace("(-","(0-") + ")"
        nums = []
        ops = []
        i = 0
        while i < len(s):
            c = s[i]
            i += 1
            if c.isdigit():
                num = int(c)
                while s[i].isdigit():
                    num = num *10 + int(s[i])
                    i += 1
                nums.append(num)
            elif c == "(":
                ops.append(c)
            elif c == ")":
                while ops and ops[-1] != "(":
                    self.cacl(nums,ops)
                ops.pop()
            else:
                while ops and ops[-1] != "(":
                    self.cacl(nums,ops)
                ops.append(c)
        return nums.pop()
    def cacl(self,nums,ops):
        y,x = nums.pop(),nums.pop()
        c = ops.pop()
        if c == "+":
            res = x + y
        else:
            res = x - y
        nums.append(res)

你可能感兴趣的:(java,算法,数据结构)