Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Analysis
- Wiki gives pseudo code and example. Very clear. See reference
Code
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> st = new Stack<Integer>();
for(String s:tokens){
if(s.equals("+")){
int j = st.pop();
int i = st.pop();
int k = i+j;
st.push(k);
}
else if(s.equals("-")){
int j = st.pop();
int i = st.pop();
int k = i-j;
st.push(k);
}
else if(s.equals("*")){
int j = st.pop();
int i = st.pop();
int k = i*j;
st.push(k);
}
else if(s.equals("/")){
int j = st.pop();
int i = st.pop();
int k = i/j;
st.push(k);
}
else{
st.push(Integer.parseInt(s));
}
}
return st.pop();
}
}
Note
- use s.equals() to compare string, do not use "=="
- stack.push(), stack.pop(), stack.peek(), stack.empty()
- int = Integer.parseInt(string)
Reference
Wiki