-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate-reverse-polish-notation.java
41 lines (37 loc) · 1.14 KB
/
evaluate-reverse-polish-notation.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
Problem link - https://leetcode.com/problems/evaluate-reverse-polish-notation/
// TC - O(N)
// SC - O(N)
class Solution {
public int evalRPN(String[] tokens) {
//postfix notation
int ans = 0;
Stack<Integer> st = new Stack<>();
for(String token: tokens){
if(token.equals("+")){
int a = st.pop();
int b = st.pop();
int sum = a + b;
st.push(sum);
} else if(token.equals("-")){
int b = st.pop();
int a = st.pop();
int diff = a - b;
st.push(diff);
} else if(token.equals("*")){
int a = st.pop();
int b = st.pop();
int prod = a * b;
st.push(prod);
} else if(token.equals("/")){
int b = st.pop();
int a = st.pop();
int quotient = a / b;
st.push(quotient);
} else {
//parse to int and push to stack
st.push(Integer.parseInt(token));
}
}
return st.peek();
}
}