LeetCode 2 Evaluate Reverse Polish Notation

原创
2016-06-07 15:42:56815浏览

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, *] - ((21)*3) - 9 [4, 13, 5, /, ] - (4 (13 / 5)) - 6 分析:

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", "//m.sbmmt.com/m/", "+"] -> (4 + (13 / 5)) -> 6

分析:后缀表达式操作。

栈的应用,如果碰见数字,则压栈,碰见运算符则弹出两个元素,对两个元素进行数学运算后结果压栈。

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack st = new Stack();
        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("//m.sbmmt.com/m/")){
                    st.push(num1/num2);
                }
            } 
        }
        return st.pop();
    }
}


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
PHP中文网
程序员·梦开始的地方
下载APP