[Leetcode] Evaluate Reverse Polish Notation (Java)

来源:互联网 发布:淘宝上买摩托车被骗了 编辑:程序博客网 时间:2024/05/22 17:26

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

计算后缀表达式的值

public class Solution {    public int evalRPN(String[] tokens) {                Stack<Integer> stack = new Stack<Integer>();        for(int i=0;i<tokens.length;i++){String tmp = tokens[i];if(tmp.equals("+")||tmp.equals("-")||tmp.equals("*")||tmp.equals("/")){int b = stack.pop();int a = stack.pop();if(tmp.equals("+"))stack.push(a+b);else if(tmp.equals("-"))stack.push(a-b);else if (tmp.equals("*")) stack.push(a*b);elsestack.push(a/b);}else stack.push(Integer.parseInt(tmp));}return stack.pop();      }}


0 0
原创粉丝点击