KK's blog

每天积累多一些

0%

LeetCode 224 Basic Calculator

LeetCode

<div>

Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.

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

Example 1:

<pre>Input: s = "1 + 1" Output: 2 </pre>

Example 2:

<pre>Input: s = " 2-1 + 2 " Output: 3 </pre>

Example 3:

<pre>Input: s = "(1+(4+5+2)-3)+(6+8)" Output: 23 </pre>

Constraints:

  • 1 <= s.length <= 3 * 10<sup>5</sup>
  • s consists of digits, '+', '-', '(', ')', and ' '.
  • s represents a valid expression.
  • '+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid).
  • '-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
  • There will be no two consecutive operators in the input.
  • Every number and running calculation will fit in a signed 32-bit integer.

</div>

题目大意:

实现字符串加减,但有括号。

算法思路:

括号题优先考虑用Stack。这里Stack不能只存数,因为括号前可以是正负,所以将这个信息以+1或-1也压入栈(栈不能混合字符和数字)
所以用一个stack,num是一个数,res是括号内的累积结果。num在处理完每一个数都要重设,res和sign在处理完每个括号都要重设。

运用模板,代码中含五种情况:空格,运算符,数字,左右括号。左括号将res和sign入栈,右括号将res和sign出栈,计算结果存在res

LeetCode 224 Basic Calculator 括号加减法, 同一层括号内求和遇括号入栈
LeetCode 227 Basic Calculator II 加减乘除, 和的每一项入栈,方便出栈计乘除
LeetCode 772 Basic Calculator III 加减乘除括号, L227的递归版

注意事项:

  1. 括号前可以是正负,所以将这个信息以+1或-1也压入栈
  2. 左括号无论前面是正负都要入栈
  3. num在处理完每一个数都要重设,res和sign在处理完每个括号都要重设

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 1-(2+3)+(4+5)
# 1+2+3
def calculate(self, s: str) -> int:
res, num, stack, sign = 0, 0, [], 1
s += '+'
for char in s:
if char == ' ':
continue
if char.isdigit():
num = num * 10 + int(char)
if char == '+':
res += sign * num
sign = 1
num = 0
if char == '-':
res += sign * num
sign = -1
num = 0
if char == '(':
stack.append(res) # [-4+]
stack.append(sign) #
sign = 1
res = 0
if char == ')':
res += sign * num # 9
prev_sign = stack.pop() # +
tmp = stack.pop() # -4
res = tmp + prev_sign * res # -4 +9
# sign = 1 next one will be +-, so num = 0 and sign doesn't matter
num = 0
# else:
# res += char
return res

算法分析:

时间复杂度为O(n),空间复杂度O(n)

Free mock interview