Skip to content

Commit 40d752c

Browse files
authored
Update 150.evaluate-reverse-polish-notation.md
1 parent ba11388 commit 40d752c

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

problems/150.evaluate-reverse-polish-notation.md

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,9 @@ https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
9292

9393
## 代码
9494

95-
代码支持:JS,Python
95+
代码支持:JS,Python,Java
96+
97+
JS Code:
9698

9799
```js
98100
/**
@@ -133,6 +135,9 @@ var evalRPN = function(tokens) {
133135

134136
```
135137

138+
139+
Python Code:
140+
136141
```python
137142
class Solution:
138143
def evalRPN(self, tokens: List[str]) -> int:
@@ -159,6 +164,32 @@ class Solution:
159164
```
160165

161166

167+
Java Code:
168+
169+
```java
170+
class Solution {
171+
public static int evalRPN(String[] tokens) {
172+
int[] numStack = new int[tokens.length / 2 + 1];
173+
int index = 0;
174+
for (String s : tokens) {
175+
if (s.equals("+")) {
176+
numStack[index - 2] += numStack[--index];
177+
} else if (s.equals("-")) {
178+
numStack[index - 2] -= numStack[--index];
179+
} else if (s.equals("*")) {
180+
numStack[index - 2] *= numStack[--index];
181+
} else if (s.equals("/")) {
182+
numStack[index - 2] /= numStack[--index];
183+
} else {
184+
numStack[index++] = Integer.parseInt(s);
185+
}
186+
}
187+
return numStack[0];
188+
}
189+
}
190+
```
191+
192+
162193
## 扩展
163194

164195
逆波兰表达式中只改变运算符的顺序,并不会改变操作数的相对顺序,这是一个重要的性质。另外逆波兰表达式完全不关心操作符的优先级,这在中缀表达式中是做不到的,这很有趣,感兴趣的可以私下查找资料研究下为什么会这样。

0 commit comments

Comments
 (0)