1. 程式人生 > >[LeetCode] 150. Evaluate Reverse Polish Notation Java

[LeetCode] 150. Evaluate Reverse Polish Notation Java

value class 題目 als eval 註意 light 程序 highlight

題目:

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

題意及分析:給出一個字符串,程序計算逆波蘭式的結果,遍歷表達式,碰到操作數入棧,碰到操作符就從棧頂取出兩個操作數,再將計算後的結果入棧,最後棧中剩余的唯一操作數就是計算結果。 這裏註意的是string類型判斷值是否相等需要用.equals。

代碼:

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack=new Stack<>();
        for(int i=0;i<tokens.length;i++){
        	String token=tokens[i];
        	if(token.equals("+")||token.equals("-")||token.equals("*")||token.equals("/")){
        		int op1=stack.pop();
        		int op2=stack.pop();
        		if(token.equals("+")){
        			stack.push(op2+op1);
        		}
        		if(token.equals("-")){
        			stack.push(op2-op1);
        		}
        		if(token.equals("*")){
        			stack.push(op2*op1);
        		}
        		if(token.equals("/")){
        			stack.push(op2/op1);
        		}
        	}else{
        		stack.push(Integer.parseInt(token));
        	}
        }
        int res=stack.peek();
        // System.out.println(res);
        return res;
    }
}

  

[LeetCode] 150. Evaluate Reverse Polish Notation Java