LeetCode150 Evaluate Reverse Polish Notation java题解

题目:

Evaluate the value of an arithmetic expression inReverse 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.Stack;public class LeetCode150_EvaluateReversePolishNotation {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubString[] s={"4","-2","/","2","-3","-","-"};System.out.println(evalRPN(s));}public static int evalRPN(String[] tokens) { int length=tokens.length; Stack<Integer> stack =new Stack<>();for(int i=0;i<length;i++) {if(!isOperator(tokens[i]))stack.push(Integer.parseInt(tokens[i]));else {int operaNum2=stack.pop();int operaNum1=stack.pop();if(tokens[i].equals("+"))stack.push(operaNum1+operaNum2);else if(tokens[i].equals("-"))stack.push(operaNum1-operaNum2);else if(tokens[i].equals("*"))stack.push(operaNum1*operaNum2);else {stack.push(operaNum1/operaNum2);}}}return stack.pop();}public static boolean isOperator(String s) { if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/"))return true; elsereturn false; }}

版权声明:本文为博主原创文章,未经博主允许不得转载。

你可以用爱得到全世界,你也可以用恨失去全世界

LeetCode150 Evaluate Reverse Polish Notation java题解

相关文章:

你感兴趣的文章:

标签云: