leetcode--evaluate-reverse-polish-notation

来源:互联网 发布:淘宝网卖家体检中心 编辑:程序博客网 时间:2024/06/01 09:01

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

分析:逆波兰表达式的计算;

建立一个栈,将每个数字压入栈,当遇到计算符事,弹出前两个数参与计算,并把结果压栈

import java.util.*;public class Solution {    public int evalRPN(String[] tokens) {        Stack<Integer> stackNum=new Stack<>();        int len=tokens.length;        for(int i=0;i<len;i++){            try{                stackNum.push(Integer.parseInt(tokens[i]));            }catch(Exception e){                String operation=tokens[i];                int numA=stackNum.pop();                int numB=stackNum.pop();                switch(operation){                    case "+":                        stackNum.push(numB+numA);                        break;                    case "-":                        stackNum.push(numB-numA);                        break;                    case "*":                        stackNum.push(numB*numA);                        break;                    case "/":                        stackNum.push(numB/numA);                        break;                }            }        }        return stackNum.pop();    }}


原创粉丝点击