leetcode - 772. Basic Calculator III

Description

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, ‘+’, ‘-’, ‘*’, ‘/’ operators, and open ‘(’ and closing parentheses ‘)’. The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1].

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Example 1:

Input: s = "1+1"
Output: 2

Example 2:

Input: s = "6-4/2"
Output: 4

Example 3:

Input: s = "2*(5+5*2)/3+(6/2+8)"
Output: 21

Constraints:

1 <= s <= 10^4
s consists of digits, '+', '-', '*', '/', '(', and ')'.
s is a valid expression.

Solution

Consider +, - as positive number and negative number, use recursive to solve parentheses. See 227. 基本计算器 II (+, -, *, /,无括号) for details.

Code

class Solution:
    def calculate(self, s: str) -> int:
        def find_closing_index(index: int) -> int:
            left_cnt = 0
            i = index
            while i < len(s):
                if s[i] == '(':
                    left_cnt += 1
                elif s[i] == ')':
                    left_cnt -= 1
                if left_cnt == 0:
                    break
                i += 1
            return i

        def helper(left: int, right: int) -> int:
            if s[left] == '(' and right == find_closing_index(left):
                return helper(left + 1, right - 1)
            op, sign = 0, '+'
            stack = []
            index = left
            while index <= right:
                if s[index].isdecimal():
                    op = op * 10 + int(s[index])
                    index += 1
                elif s[index] in ('+', '-', '*', '/'):
                    if sign in ('+', '-'):
                        stack.append(op * (1 if sign == '+' else -1))
                    elif sign == '*':
                        stack[-1] *= op
                    elif sign == '/':
                        stack[-1] = int(stack[-1] / op)
                    op = 0
                    sign = s[index]
                    index += 1
                elif s[index] == '(':
                    index_right = find_closing_index(index)
                    op = helper(index, index_right)
                    index = index_right + 1
                else:
                    index += 1
            if sign in ('+', '-'):
                stack.append(op * (1 if sign == '+' else -1))
            elif sign == '*':
                stack[-1] *= op
            elif sign == '/':
                stack[-1] = int(stack[-1] / op)
            return sum(stack)
        return helper(0, len(s) - 1)
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值