Skip to content

Commit

Permalink
fix: 227
Browse files Browse the repository at this point in the history
  • Loading branch information
robot committed Jun 15, 2021
1 parent 7aeb080 commit 71994dc
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions problems/227.basic-calculator-ii.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,71 @@ class Solution:
- 时间复杂度:$O(N)$
- 空间复杂度:$O(N)$

## 两个栈

### 思路

使用两个栈适用范围更广, 能解决 + - \* / ^ % ( ) 等表达式问题,是一种经典的做法。比如 [1896. 反转表达式值的最少操作次数](https://leetcode-cn.com/problems/minimum-cost-to-change-the-final-value-of-expression/) 就可以使用双栈来解决。

这里的两个栈分别用于存储操作数和非操作数,不妨:

- 用 nums 存储操作数
- 用 ops 存储非操作数

整体的思路也是类似的,我们一起来看下。

### 代码

代码支持:Python

Python Code:

```py
class Solution:
def calculate(self, s: str) -> int:
s = '(' + s + ')'
n = len(s)
i = 0
stack_ops = [] # 存储字符串的栈
stack_nums = [] # 存储数字的栈
while i < n:
if s[i] in ' ':
i += 1
continue
elif '0' <= s[i] <= '9':
# 是数字
num = ''
while i < n and s[i].isdigit():
num += s[i]
i += 1
i -= 1
stack_nums.append(int(num))
if not stack_ops:
i += 1
continue
op = stack_ops.pop()
num = stack_nums.pop()
if op == "+":
num *= 1
elif op == "-":
num *= -1
elif op == "*":
num = stack_nums.pop() * num
elif op == "/":
if num ^ stack_nums[-1] > 0: num = stack_nums.pop() // num
else: num = (stack_nums.pop() + num - 1) // num
stack_nums.append(num)
else:
stack_ops.append(s[i])
i += 1
return sum(stack_nums)
```

**复杂度分析**

- 时间复杂度:$O(N)$
- 空间复杂度:$O(N)$

## 扩展

224. 基本计算器 和这道题差不多,官方难度困难。就是多了个括号而已。所以基本上可以看做是这道题的扩展。题目描述:
Expand Down

0 comments on commit 71994dc

Please sign in to comment.