Evaluate Reverse Polish Notation

来源:互联网 发布:mac 照片 文件夹 分类 编辑:程序博客网 时间:2024/06/03 19:49

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

关键点:stack

思路:遇到数字则进栈,遇到操作符则取出栈顶的两个元素进行运算,要注意的是取出的元素和操作数顺序的关系。

代码:

public class Solution {    public int evalRPN(String[] tokens) {        Stack<Integer> stack = new Stack<Integer>();        for (int i = 0; i < tokens.length; i++) {            switch (tokens[i]) {            case "+":                stack.push(stack.pop() + stack.pop());            break;            case "-":                stack.push(-stack.pop() + stack.pop());                break;            case "*":                stack.push(stack.pop() * stack.pop());                break;            case "/":                int n1 = stack.pop(), n2 = stack.pop();                stack.push(n2 / n1);                break;            default:                stack.push(Integer.parseInt(tokens[i]));            }        }        return stack.pop();    }}


0 0
原创粉丝点击