-
Notifications
You must be signed in to change notification settings - Fork 1
/
EvaluateReversePolishNotation.java
48 lines (41 loc) · 1.25 KB
/
EvaluateReversePolishNotation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
// https://leetcode.com/problems/evaluate-reverse-polish-notation/
public class EvaluateReversePolishNotation {
private static final Set<String> OPS = new HashSet<>(
Arrays.asList("+", "-", "*", "/")
);
private final String[] input;
public EvaluateReversePolishNotation(String[] input) {
this.input = input;
}
public int solution() {
Stack<Integer> s = new Stack<>();
for (String t : input) {
if (!OPS.contains(t)) {
s.push(Integer.parseInt(t));
} else {
int b = s.pop();
int a = s.pop();
switch (t) {
case "+":
s.push(a + b);
break;
case "-":
s.push(a - b);
break;
case "*":
s.push(a * b);
break;
default:
s.push(a / b);
break;
}
}
}
return s.pop();
}
}