Skip to content

Commit 691eb7c

Browse files
committed
+ problem 224
1 parent 3641bf5 commit 691eb7c

File tree

5 files changed

+176
-0
lines changed

5 files changed

+176
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# 224. Basic Calculator
2+
Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return *the result of the evaluation*.
3+
4+
**Note:** You are **not** allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`.
5+
6+
#### Example 1:
7+
<pre>
8+
<strong>Input:</strong> s = "1 + 1"
9+
<strong>Output:</strong> 2
10+
</pre>
11+
12+
#### Example 2:
13+
<pre>
14+
<strong>Input:</strong> s = " 2-1 + 2 "
15+
<strong>Output:</strong> 3
16+
</pre>
17+
18+
#### Example 3:
19+
<pre>
20+
<strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
21+
<strong>Output:</strong> 23
22+
</pre>
23+
24+
#### Constraints:
25+
* <code>1 <= s.length <= 3 * 10<sup>5</sup></code>
26+
* `s` consists of digits, `'+'`, `'-'`, `'('`, `')'`, and `' '`.
27+
* `s` represents a valid expression.
28+
* `'+'` is **not** used as a unary operation (i.e., `"+1"` and `"+(2 + 3)"` is invalid).
29+
* `'-'` could be used as a unary operation (i.e., `"-1"` and `"-(2 + 3)"` is valid).
30+
* There will be no two consecutive operators in the input.
31+
* Every number and running calculation will fit in a signed 32-bit integer.
32+
33+
## Solutions (Python)
34+
35+
### 1. Solution
36+
```Python
37+
class Solution:
38+
def calculate(self, s: str) -> int:
39+
s = s.replace(' ', '')
40+
negstack = [False]
41+
stack = []
42+
ret = 0
43+
44+
for i in range(len(s)):
45+
if s[i] == '(':
46+
if i == 0 or s[i - 1] != '-':
47+
negstack.append(negstack[-1])
48+
else:
49+
negstack.append(not negstack[-1])
50+
elif s[i] == ')':
51+
negstack.pop()
52+
elif s[i] == '+':
53+
stack.append('-' if negstack[-1] else '+')
54+
elif s[i] == '-':
55+
if stack == [] or isinstance(stack[-1], str):
56+
stack.append(0)
57+
stack.append('+' if negstack[-1] else '-')
58+
else:
59+
if stack == [] or isinstance(stack[-1], str):
60+
stack.append(0)
61+
stack[-1] = stack[-1] * 10 + int(s[i])
62+
63+
ret = stack[0]
64+
65+
for i in range(2, len(stack), 2):
66+
ret += stack[i] if stack[i - 1] == '+' else -stack[i]
67+
68+
return ret
69+
```
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# 224. 基本计算器
2+
给你一个字符串表达式 `s` ,请你实现一个基本计算器来计算并返回它的值。
3+
4+
注意:不允许使用任何将字符串作为数学表达式计算的内置函数,比如 `eval()`
5+
6+
#### 示例 1:
7+
<pre>
8+
<strong>输入:</strong> s = "1 + 1"
9+
<strong>输出:</strong> 2
10+
</pre>
11+
12+
#### 示例 2:
13+
<pre>
14+
<strong>输入:</strong> s = " 2-1 + 2 "
15+
<strong>输出:</strong> 3
16+
</pre>
17+
18+
#### 示例 3:
19+
<pre>
20+
<strong>输入:</strong> s = "(1+(4+5+2)-3)+(6+8)"
21+
<strong>输出:</strong> 23
22+
</pre>
23+
24+
#### 提示:
25+
* <code>1 <= s.length <= 3 * 10<sup>5</sup></code>
26+
* `s` 由数字、`'+'``'-'``'('``')'`、和 `' '` 组成
27+
* `s` 表示一个有效的表达式
28+
* `'+'` 不能用作一元运算(例如, `"+1"``"+(2 + 3)"` 无效)
29+
* `'-'` 可以用作一元运算(即 `"-1"``"-(2 + 3)"` 是有效的)
30+
* 输入中不存在两个连续的操作符
31+
* 每个数字和运行的计算将适合于一个有符号的 32位 整数
32+
33+
## 题解 (Python)
34+
35+
### 1. 题解
36+
```Python
37+
class Solution:
38+
def calculate(self, s: str) -> int:
39+
s = s.replace(' ', '')
40+
negstack = [False]
41+
stack = []
42+
ret = 0
43+
44+
for i in range(len(s)):
45+
if s[i] == '(':
46+
if i == 0 or s[i - 1] != '-':
47+
negstack.append(negstack[-1])
48+
else:
49+
negstack.append(not negstack[-1])
50+
elif s[i] == ')':
51+
negstack.pop()
52+
elif s[i] == '+':
53+
stack.append('-' if negstack[-1] else '+')
54+
elif s[i] == '-':
55+
if stack == [] or isinstance(stack[-1], str):
56+
stack.append(0)
57+
stack.append('+' if negstack[-1] else '-')
58+
else:
59+
if stack == [] or isinstance(stack[-1], str):
60+
stack.append(0)
61+
stack[-1] = stack[-1] * 10 + int(s[i])
62+
63+
ret = stack[0]
64+
65+
for i in range(2, len(stack), 2):
66+
ret += stack[i] if stack[i - 1] == '+' else -stack[i]
67+
68+
return ret
69+
```
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
def calculate(self, s: str) -> int:
3+
s = s.replace(' ', '')
4+
negstack = [False]
5+
stack = []
6+
ret = 0
7+
8+
for i in range(len(s)):
9+
if s[i] == '(':
10+
if i == 0 or s[i - 1] != '-':
11+
negstack.append(negstack[-1])
12+
else:
13+
negstack.append(not negstack[-1])
14+
elif s[i] == ')':
15+
negstack.pop()
16+
elif s[i] == '+':
17+
stack.append('-' if negstack[-1] else '+')
18+
elif s[i] == '-':
19+
if stack == [] or isinstance(stack[-1], str):
20+
stack.append(0)
21+
stack.append('+' if negstack[-1] else '-')
22+
else:
23+
if stack == [] or isinstance(stack[-1], str):
24+
stack.append(0)
25+
stack[-1] = stack[-1] * 10 + int(s[i])
26+
27+
ret = stack[0]
28+
29+
for i in range(2, len(stack), 2):
30+
ret += stack[i] if stack[i - 1] == '+' else -stack[i]
31+
32+
return ret

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@
189189
[221][221l] |[Maximal Square][221] |![rs]
190190
[222][222l] |[Count Complete Tree Nodes][222] |![py]
191191
[223][223l] |[Rectangle Area][223] |![rb]&nbsp;&nbsp;![rs]
192+
[224][224l] |[Basic Calculator][224] |![py]
192193
[225][225l] |[Implement Stack using Queues][225] |![rs]
193194
[226][226l] |[Invert Binary Tree][226] |![py]
194195
[227][227l] |[Basic Calculator II][227] |![py]
@@ -1868,6 +1869,7 @@
18681869
[221]:Problemset/0221-Maximal%20Square/README.md#221-maximal-square
18691870
[222]:Problemset/0222-Count%20Complete%20Tree%20Nodes/README.md#222-count-complete-tree-nodes
18701871
[223]:Problemset/0223-Rectangle%20Area/README.md#223-rectangle-area
1872+
[224]:Problemset/0224-Basic%20Calculator/README.md#224-basic-calculator
18711873
[225]:Problemset/0225-Implement%20Stack%20using%20Queues/README.md#225-implement-stack-using-queues
18721874
[226]:Problemset/0226-Invert%20Binary%20Tree/README.md#226-invert-binary-tree
18731875
[227]:Problemset/0227-Basic%20Calculator%20II/README.md#227-basic-calculator-ii
@@ -3540,6 +3542,7 @@
35403542
[221l]:https://leetcode.com/problems/maximal-square/
35413543
[222l]:https://leetcode.com/problems/count-complete-tree-nodes/
35423544
[223l]:https://leetcode.com/problems/rectangle-area/
3545+
[224l]:https://leetcode.com/problems/basic-calculator/
35433546
[225l]:https://leetcode.com/problems/implement-stack-using-queues/
35443547
[226l]:https://leetcode.com/problems/invert-binary-tree/
35453548
[227l]:https://leetcode.com/problems/basic-calculator-ii/

README_CN.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@
189189
[221][221l] |[最大正方形][221] |![rs]
190190
[222][222l] |[完全二叉树的节点个数][222] |![py]
191191
[223][223l] |[矩形面积][223] |![rb]&nbsp;&nbsp;![rs]
192+
[224][224l] |[基本计算器][224] |![py]
192193
[225][225l] |[用队列实现栈][225] |![rs]
193194
[226][226l] |[翻转二叉树][226] |![py]
194195
[227][227l] |[基本计算器 II][227] |![py]
@@ -1868,6 +1869,7 @@
18681869
[221]:Problemset/0221-Maximal%20Square/README_CN.md#221-最大正方形
18691870
[222]:Problemset/0222-Count%20Complete%20Tree%20Nodes/README_CN.md#222-完全二叉树的节点个数
18701871
[223]:Problemset/0223-Rectangle%20Area/README_CN.md#223-矩形面积
1872+
[224]:Problemset/0224-Basic%20Calculator/README_CN.md#224-基本计算器
18711873
[225]:Problemset/0225-Implement%20Stack%20using%20Queues/README_CN.md#225-用队列实现栈
18721874
[226]:Problemset/0226-Invert%20Binary%20Tree/README_CN.md#226-翻转二叉树
18731875
[227]:Problemset/0227-Basic%20Calculator%20II/README_CN.md#227-基本计算器-ii
@@ -3540,6 +3542,7 @@
35403542
[221l]:https://leetcode.cn/problems/maximal-square/
35413543
[222l]:https://leetcode.cn/problems/count-complete-tree-nodes/
35423544
[223l]:https://leetcode.cn/problems/rectangle-area/
3545+
[224l]:https://leetcode.cn/problems/basic-calculator/
35433546
[225l]:https://leetcode.cn/problems/implement-stack-using-queues/
35443547
[226l]:https://leetcode.cn/problems/invert-binary-tree/
35453548
[227l]:https://leetcode.cn/problems/basic-calculator-ii/

0 commit comments

Comments
 (0)