Skip to content

Commit 534f2ff

Browse files
committed
+ problem 227
1 parent e73d846 commit 534f2ff

File tree

5 files changed

+219
-0
lines changed

5 files changed

+219
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# 227. Basic Calculator II
2+
Given a string `s` which represents an expression, *evaluate this expression and return its value*.
3+
4+
The integer division should truncate toward zero.
5+
6+
You may assume that the given expression is always valid. All intermediate results will be in the range of <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.
7+
8+
**Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`.
9+
10+
#### Example 1:
11+
<pre>
12+
<strong>Input:</strong> s = "3+2*2"
13+
<strong>Output:</strong> 7
14+
</pre>
15+
16+
#### Example 2:
17+
<pre>
18+
<strong>Input:</strong> s = " 3/2 "
19+
<strong>Output:</strong> 1
20+
</pre>
21+
22+
#### Example 3:
23+
<pre>
24+
<strong>Input:</strong> s = " 3+5 / 2 "
25+
<strong>Output:</strong> 5
26+
</pre>
27+
28+
#### Constraints:
29+
* <code>1 <= s.length <= 3 * 10<sup>5</sup></code>
30+
* `s` consists of integers and operators `('+', '-', '*', '/')` separated by some number of spaces.
31+
* `s` represents **a valid expression**.
32+
* All the integers in the expression are non-negative integers in the range <code>[0, 2<sup>31</sup> - 1]</code>.
33+
* The answer is **guaranteed** to fit in a **32-bit integer**.
34+
35+
## Solutions (Python)
36+
37+
### 1. Solution
38+
```Python
39+
class Solution:
40+
def calculate(self, s: str) -> int:
41+
isint = False
42+
lastsign = None
43+
stack = []
44+
ret = 0
45+
46+
for ch in s:
47+
if ch in "+-*/":
48+
if lastsign == '*':
49+
x, _ = stack.pop(), stack.pop()
50+
stack[-1] *= x
51+
elif lastsign == '/':
52+
x, _ = stack.pop(), stack.pop()
53+
stack[-1] //= x
54+
55+
isint = False
56+
lastsign = ch
57+
stack.append(ch)
58+
elif ch.isdigit():
59+
if isint:
60+
stack[-1] = stack[-1] * 10 + int(ch)
61+
else:
62+
isint = True
63+
stack.append(int(ch))
64+
65+
if lastsign == '*':
66+
x, _ = stack.pop(), stack.pop()
67+
stack[-1] *= x
68+
elif lastsign == '/':
69+
x, _ = stack.pop(), stack.pop()
70+
stack[-1] //= x
71+
72+
lastsign = '+'
73+
74+
for elem in stack:
75+
if isinstance(elem, int):
76+
if lastsign == '+':
77+
ret += elem
78+
elif lastsign == '-':
79+
ret -= elem
80+
else:
81+
lastsign = elem
82+
83+
return ret
84+
```
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# 227. 基本计算器 II
2+
给你一个字符串表达式 `s` ,请你实现一个基本计算器来计算并返回它的值。
3+
4+
整数除法仅保留整数部分。
5+
6+
你可以假设给定的表达式总是有效的。所有中间结果将在 <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code> 的范围内。
7+
8+
**注意:**不允许使用任何将字符串作为数学表达式计算的内置函数,比如 `eval()`
9+
10+
#### 示例 1:
11+
<pre>
12+
<strong>输入:</strong> s = "3+2*2"
13+
<strong>输出:</strong> 7
14+
</pre>
15+
16+
#### 示例 2:
17+
<pre>
18+
<strong>输入:</strong> s = " 3/2 "
19+
<strong>输出:</strong> 1
20+
</pre>
21+
22+
#### 示例 3:
23+
<pre>
24+
<strong>输入:</strong> s = " 3+5 / 2 "
25+
<strong>输出:</strong> 5
26+
</pre>
27+
28+
#### 提示:
29+
* <code>1 <= s.length <= 3 * 10<sup>5</sup></code>
30+
* `s` 由整数和算符 `('+', '-', '*', '/')` 组成,中间由一些空格隔开
31+
* `s` 表示一个 **有效表达式**
32+
* 表达式中的所有整数都是非负整数,且在范围 <code>[0, 2<sup>31</sup> - 1]</code> 内
33+
* 题目数据保证答案是一个 **32-bit 整数**
34+
35+
## 题解 (Python)
36+
37+
### 1. 题解
38+
```Python
39+
class Solution:
40+
def calculate(self, s: str) -> int:
41+
isint = False
42+
lastsign = None
43+
stack = []
44+
ret = 0
45+
46+
for ch in s:
47+
if ch in "+-*/":
48+
if lastsign == '*':
49+
x, _ = stack.pop(), stack.pop()
50+
stack[-1] *= x
51+
elif lastsign == '/':
52+
x, _ = stack.pop(), stack.pop()
53+
stack[-1] //= x
54+
55+
isint = False
56+
lastsign = ch
57+
stack.append(ch)
58+
elif ch.isdigit():
59+
if isint:
60+
stack[-1] = stack[-1] * 10 + int(ch)
61+
else:
62+
isint = True
63+
stack.append(int(ch))
64+
65+
if lastsign == '*':
66+
x, _ = stack.pop(), stack.pop()
67+
stack[-1] *= x
68+
elif lastsign == '/':
69+
x, _ = stack.pop(), stack.pop()
70+
stack[-1] //= x
71+
72+
lastsign = '+'
73+
74+
for elem in stack:
75+
if isinstance(elem, int):
76+
if lastsign == '+':
77+
ret += elem
78+
elif lastsign == '-':
79+
ret -= elem
80+
else:
81+
lastsign = elem
82+
83+
return ret
84+
```
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution:
2+
def calculate(self, s: str) -> int:
3+
isint = False
4+
lastsign = None
5+
stack = []
6+
ret = 0
7+
8+
for ch in s:
9+
if ch in "+-*/":
10+
if lastsign == '*':
11+
x, _ = stack.pop(), stack.pop()
12+
stack[-1] *= x
13+
elif lastsign == '/':
14+
x, _ = stack.pop(), stack.pop()
15+
stack[-1] //= x
16+
17+
isint = False
18+
lastsign = ch
19+
stack.append(ch)
20+
elif ch.isdigit():
21+
if isint:
22+
stack[-1] = stack[-1] * 10 + int(ch)
23+
else:
24+
isint = True
25+
stack.append(int(ch))
26+
27+
if lastsign == '*':
28+
x, _ = stack.pop(), stack.pop()
29+
stack[-1] *= x
30+
elif lastsign == '/':
31+
x, _ = stack.pop(), stack.pop()
32+
stack[-1] //= x
33+
34+
lastsign = '+'
35+
36+
for elem in stack:
37+
if isinstance(elem, int):
38+
if lastsign == '+':
39+
ret += elem
40+
elif lastsign == '-':
41+
ret -= elem
42+
else:
43+
lastsign = elem
44+
45+
return ret

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@
156156
[223][223l] |[Rectangle Area][223] |![rb]&nbsp;&nbsp;![rs]
157157
[225][225l] |[Implement Stack using Queues][225] |![rs]
158158
[226][226l] |[Invert Binary Tree][226] |![py]
159+
[227][227l] |[Basic Calculator II][227] |![py]
159160
[228][228l] |[Summary Ranges][228] |![py]
160161
[229][229l] |[Majority Element II][229] |![rs]
161162
[230][230l] |[Kth Smallest Element in a BST][230] |![rb]
@@ -1435,6 +1436,7 @@
14351436
[223]:Problemset/0223-Rectangle%20Area/README.md#223-rectangle-area
14361437
[225]:Problemset/0225-Implement%20Stack%20using%20Queues/README.md#225-implement-stack-using-queues
14371438
[226]:Problemset/0226-Invert%20Binary%20Tree/README.md#226-invert-binary-tree
1439+
[227]:Problemset/0227-Basic%20Calculator%20II/README.md#227-basic-calculator-ii
14381440
[228]:Problemset/0228-Summary%20Ranges/README.md#228-summary-ranges
14391441
[229]:Problemset/0229-Majority%20Element%20II/README.md#229-majority-element-ii
14401442
[230]:Problemset/0230-Kth%20Smallest%20Element%20in%20a%20BST/README.md#230-kth-smallest-element-in-a-bst
@@ -2711,6 +2713,7 @@
27112713
[223l]:https://leetcode.com/problems/rectangle-area/
27122714
[225l]:https://leetcode.com/problems/implement-stack-using-queues/
27132715
[226l]:https://leetcode.com/problems/invert-binary-tree/
2716+
[227l]:https://leetcode.com/problems/basic-calculator-ii/
27142717
[228l]:https://leetcode.com/problems/summary-ranges/
27152718
[229l]:https://leetcode.com/problems/majority-element-ii/
27162719
[230l]:https://leetcode.com/problems/kth-smallest-element-in-a-bst/

README_CN.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@
156156
[223][223l] |[矩形面积][223] |![rb]&nbsp;&nbsp;![rs]
157157
[225][225l] |[用队列实现栈][225] |![rs]
158158
[226][226l] |[翻转二叉树][226] |![py]
159+
[227][227l] |[基本计算器 II][227] |![py]
159160
[228][228l] |[汇总区间][228] |![py]
160161
[229][229l] |[多数元素 II][229] |![rs]
161162
[230][230l] |[二叉搜索树中第K小的元素][230] |![rb]
@@ -1435,6 +1436,7 @@
14351436
[223]:Problemset/0223-Rectangle%20Area/README_CN.md#223-矩形面积
14361437
[225]:Problemset/0225-Implement%20Stack%20using%20Queues/README_CN.md#225-用队列实现栈
14371438
[226]:Problemset/0226-Invert%20Binary%20Tree/README_CN.md#226-翻转二叉树
1439+
[227]:Problemset/0227-Basic%20Calculator%20II/README_CN.md#227-基本计算器-ii
14381440
[228]:Problemset/0228-Summary%20Ranges/README_CN.md#228-汇总区间
14391441
[229]:Problemset/0229-Majority%20Element%20II/README_CN.md#229-多数元素-ii
14401442
[230]:Problemset/0230-Kth%20Smallest%20Element%20in%20a%20BST/README_CN.md#230-二叉搜索树中第k小的元素
@@ -2711,6 +2713,7 @@
27112713
[223l]:https://leetcode.cn/problems/rectangle-area/
27122714
[225l]:https://leetcode.cn/problems/implement-stack-using-queues/
27132715
[226l]:https://leetcode.cn/problems/invert-binary-tree/
2716+
[227l]:https://leetcode.cn/problems/basic-calculator-ii/
27142717
[228l]:https://leetcode.cn/problems/summary-ranges/
27152718
[229l]:https://leetcode.cn/problems/majority-element-ii/
27162719
[230l]:https://leetcode.cn/problems/kth-smallest-element-in-a-bst/

0 commit comments

Comments
 (0)