美文网首页
150. Evaluate Reverse Polish Not

150. Evaluate Reverse Polish Not

作者: 7ccc099f4608 | 来源:发表于2020-03-18 13:19 被阅读0次

https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/

image.png

(图片来源https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/

日期 是否一次通过 comment
2020-03-18 0

递归

public int evalRPN(String[] tokens) {
        int res = 0;

        if(tokens == null || tokens.length <= 0) {
            return res;
        }

        Stack<Integer> stk = new Stack<>();
        int a = 0, b = 0;
        for(String s : tokens) {
            if(s.equals("+")) {
                a = stk.pop();
                b = stk.pop();

                stk.push(b+a);
            } else if(s.equals("-")) {
                a = stk.pop();
                b = stk.pop();

                stk.push(b-a);
            }  else if(s.equals("*")) {
                a = stk.pop();
                b = stk.pop();

                stk.push(b*a);
            }  else if(s.equals("/")) {
                a = stk.pop();
                b = stk.pop();

                stk.push(b/a);
            } else {
                stk.push(Integer.parseInt(s));
            }
        }

        return stk.pop();
    }

相关文章

网友评论

      本文标题:150. Evaluate Reverse Polish Not

      本文链接:https://www.haomeiwen.com/subject/wgvqyhtx.html