首页 > 代码库 > [LeetCode]-Evaluate Reverse Polish Notation

[LeetCode]-Evaluate Reverse Polish Notation

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

 1 /* 2 *解题思路: 3 *借助辅助栈来完成逆波兰表达式的计算 4 *1.遍历数组,当前字符串为数字时入栈; 5 *2.为算符时,弹出栈顶的两个元素,完成计算,计算结果入栈; 6 *3.遍历完成,当栈非空时,返回栈顶元素,计算完成。 7 */ 8 public class Solution { 9     public int evalRPN(String[] tokens) {10         int factor1, factor2, result=0;11         Stack<String> stack = new Stack<String>();12         int len = tokens.length;13         for( int i=0; i<len; i++ ){14             if( tokens[i].equals("+") ){15                 factor1 = Integer.parseInt( stack.pop() );16                 factor2 = Integer.parseInt( stack.pop() );17                 result = factor1 + factor2;18                 stack.push(result+"");19                 20             }else if( tokens[i].equals("-") ){21                 factor1 = Integer.parseInt( stack.pop() );22                 factor2 = Integer.parseInt( stack.pop() );23                 result = factor2 - factor1;24                 stack.push(result+"");25                 26             }else if( tokens[i].equals("*") ){27                 factor1 = Integer.parseInt( stack.pop() );28                 factor2 = Integer.parseInt( stack.pop() );29                 result = factor1 * factor2;30                 stack.push(result+"");31                 32             }else if( tokens[i].equals("/") ){33                 factor1 = Integer.parseInt( stack.pop() );34                 factor2 = Integer.parseInt( stack.pop() );35                 result = factor2 / factor1;36                 stack.push(result+"");37                 38             }else{39                 stack.push( tokens[i] );40             }41         }42         43         if( !stack.isEmpty() )44             result = Integer.parseInt( stack.pop() );45         return result;    46     }47 }

 



[LeetCode]-Evaluate Reverse Polish Notation