forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvaluateReversePolishNotation.java
40 lines (34 loc) · 1.02 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
class Solution {
// TC : O(n)
public int evalRPN(String[] tokens) {
Stack<String> st = new Stack<>();
for(String el: tokens){
if(isOperator(el)){
int el2 = Integer.parseInt(st.pop());
int el1 = Integer.parseInt(st.pop());
int ans = 0;
if(el.equals("*")){
ans = el1 *el2;
} else if(el.equals("/")){
ans = el1/el2;
}else if(el.equals("+")){
ans = el1 +el2;
}else if(el.equals("-")){
ans = el1 -el2;
}
st.push(ans+"");
} else {
// operand
st.push(el);
}
}
return Integer.parseInt(st.peek());
}
private boolean isOperator(String el){
if(el.equals("*") || el.equals("+") || el.equals("-") || el.equals("/")){
return true;
} else {
return false;
}
}
}