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

遍历初始字符串数组, 
若当前字符为 运算符 ,则从栈中弹出两个元素,并用该运算符对它们进行运算,然后再将运算结果压入栈 

若读到的是数字,则直接将其压入栈,不作其他操作 

import java.util.*;  
public class EvalRPN {  
     public static void main(String[] args) {  
      String[] tokens= {"4", "13", "5", "/", "+"};  
      LinkedList arr =new LinkedList();  
      
      for(String token :tokens){  
          if( (token=="+") || (token=="-") || (token=="*") || token=="/" ){  //也可以用equals
              //System.out.println("1");  
          Integer a=arr.pop();  //出栈两个
          Integer b=arr.pop();  
          Integer c=0;  
          if(token=="+") {  
               c=b+a;                 
          }else if(token=="-") {  
               c=b-a;  
          } else if(token=="*") {  
               c=b*a;  
          } else if(token=="/") {  
               c=b/a;  
          }  
              arr.push(c);  //得到的结果入栈
          }else {  
              arr.push(Integer.valueOf(token));  //如果是数字就入栈
          }  
                  
     }  
     System.out.println(arr.pop());  
     }  
   
}  

方法二:利用异常机制https://blog.csdn.net/weixin_31017205/article/details/80033877

import java.util.Stack;  
public class Solution {     
    public int evalRPN(String[] tokens) {          
        Stack stack = new Stack();          
        for(int i = 0;i

你可能感兴趣的:(笔试题(java实现))