LeetCode 2 Evaluate Reverse Polish Notation


Evaluate the value of arithmetic expression in Reverse Polish Notation.
Valid operator 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
解析:接尾辞式の操作.
スタックの応用、もし数字にぶつかるならば、スタックを押さえて、演算子にぶつかるならば2つの要素を弾き出して、2つの要素に対して数学の演算を行った後に結果はスタックを押さえます.
public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> st = new Stack<Integer>();
        for(String token : tokens){
            if(token.matches("-?[0-9]+")){
                st.push(Integer.parseInt(token));
            }else{
                int num2 = st.pop();
                int num1 = st.pop();
                if(token.equals("+")){
                    st.push(num1+num2);
                }else if(token.equals("-")){
                    st.push(num1-num2);
                }else if(token.equals("*")){
                    st.push(num1*num2);
                }else if(token.equals("/")){
                    st.push(num1/num2);
                }
            } 
        }
        return st.pop();
    }
}