1. 程式人生 > >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
遍歷初始字串陣列, 
若當前字元為 運算子 ,則從棧中彈出兩個元素,並用該運算子對它們進行運算,然後再將運算結果壓入棧 

若讀到的是數字,則直接將其壓入棧,不作其他操作 

import java.util.*;  
public class EvalRPN {  
     public static void main(String[] args) {  
      String[] tokens= {"4", "13", "5", "/", "+"};  
      LinkedList<Integer> arr =new LinkedList<Integer>();  
      
      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());  
     }  
   
}  
import java.util.Stack;  
public class Solution {     
    public int evalRPN(String[] tokens) {          
        Stack<Integer> stack = new Stack<Integer>();          
        for(int i = 0;i<tokens.length;i++){              
            try{                  
                int num = Integer.parseInt(tokens[i]);                  
                stack.add(num);              
            }catch (Exception e) {  
                int b = stack.pop();                  
                int a = stack.pop();                  
                stack.add(get(a, b, tokens[i]));              
            }          
        }          
        return stack.pop();      
    }     
    private int get(int a,int b,String operator){          
        switch (operator) {          
            case "+":            return a+b;         
            case "-":            return a-b;          
              
            case "*":            return a*b;          
            case "/":            return a/b;          
            default:            return 0;          
        }      
    }  
}