File tree Expand file tree Collapse file tree 1 file changed +32
-1
lines changed Expand file tree Collapse file tree 1 file changed +32
-1
lines changed Original file line number Diff line number Diff line change @@ -92,7 +92,9 @@ https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
92
92
93
93
## 代码
94
94
95
- 代码支持:JS,Python
95
+ 代码支持:JS,Python,Java
96
+
97
+ JS Code:
96
98
97
99
``` js
98
100
/**
@@ -133,6 +135,9 @@ var evalRPN = function(tokens) {
133
135
134
136
```
135
137
138
+
139
+ Python Code:
140
+
136
141
``` python
137
142
class Solution :
138
143
def evalRPN (self , tokens : List[str ]) -> int :
@@ -159,6 +164,32 @@ class Solution:
159
164
```
160
165
161
166
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
+
162
193
## 扩展
163
194
164
195
逆波兰表达式中只改变运算符的顺序,并不会改变操作数的相对顺序,这是一个重要的性质。另外逆波兰表达式完全不关心操作符的优先级,这在中缀表达式中是做不到的,这很有趣,感兴趣的可以私下查找资料研究下为什么会这样。
You can’t perform that action at this time.
0 commit comments