Leetcode 150.逆波兰表达式求值

逆波兰表达式求值

根据逆波兰表示法,求表达式的值。

有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

说明:

  • 整数除法只保留整数部分。
  • 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

示例 1:

输入: ["2", "1", "+", "3", "*"]

输出: 9

解释: ((2 + 1) * 3) = 9

 1 class Solution {
 2     public int evalRPN(String[] tokens) {
 3         Stack<String> stack=new Stack<String>();
 4         int n=tokens.length;
 5         for(int i=n-1;i>=0;i--){
 6             stack.push(tokens[i]);
 7         }
 8         String valide="+-*/";
 9         int result=0;
10         while(!stack.isEmpty()){
11             String value=stack.pop();
12             if(valide.contains(value)||stack.isEmpty()){
13                 continue;
14             }else{
15                 String value2=stack.pop();
16                 String op=stack.pop();
17                 int temp=0;
18                 if(op.equals('+')){
19                     temp=Integer.valueOf(value)+Integer.valueOf(value2);
20                 }else if(op.equals('-')){
21                     temp=Integer.valueOf(value)-Integer.valueOf(value2);
22                 }else if(op.equals('*')){
23                     temp=Integer.valueOf(value)*Integer.valueOf(value2);
24                 }else{
25                     temp=Integer.valueOf(value)/Integer.valueOf(value2);
26                 }
27                 stack.push(temp+"");
28                 result=temp;
29             }
30         }
31         return result;
32     }
33 }
原文地址:https://www.cnblogs.com/kexinxin/p/10195997.html