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/
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
137142class 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逆波兰表达式中只改变运算符的顺序,并不会改变操作数的相对顺序,这是一个重要的性质。另外逆波兰表达式完全不关心操作符的优先级,这在中缀表达式中是做不到的,这很有趣,感兴趣的可以私下查找资料研究下为什么会这样。
You can’t perform that action at this time.
0 commit comments