leetcode - 772. Basic Calculator III
2023-12-24 22:35:52
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)
文章来源:https://blog.csdn.net/sinat_41679123/article/details/135183018
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!