Skip to content

Commit 52d0b2b

Browse files
committed
Evaluate Reverse Polish Notation: AC
1 parent 79c6fef commit 52d0b2b

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed
Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,32 @@
11
package leetcode.medium.page2;
22

3+
import java.util.Stack;
4+
35
public class EvaluateReversePolishNotation {
46
public int evalRPN(String[] tokens) {
5-
return 0;
7+
Stack<Integer> stack = new Stack<>();
8+
9+
for (String c : tokens) {
10+
if (c.equals("+") || c.equals("-") || c.equals("*") || c.equals("/")) {
11+
int result = 0;
12+
Integer a = stack.pop();
13+
Integer b = stack.pop();
14+
result += calculate(b, a, c);
15+
stack.push(result);
16+
} else {
17+
stack.push(Integer.valueOf(c));
18+
}
19+
}
20+
return stack.pop();
21+
}
22+
23+
private int calculate(int a, int b, String operator) {
24+
switch (operator) {
25+
case "+": return a + b;
26+
case "-": return a - b;
27+
case "*": return a * b;
28+
case "/": return a / b;
29+
default: return 0;
30+
}
631
}
732
}

LeetCodePrj/Java/leetcode/medium/page2/MediumPage2.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,10 @@ public void testSortList() {
1717
ListNode sortedList = sortList.sortList(node);
1818
}
1919

20+
@Test
21+
public void testEvalRPN() {
22+
String[] input = new String[] {"2", "1", "+", "3", "*"};
23+
EvaluateReversePolishNotation evalRPN = new EvaluateReversePolishNotation();
24+
System.out.println(evalRPN.evalRPN(input));
25+
}
2026
}

0 commit comments

Comments
 (0)