LintCode : 逆波蘭表達式求值

逆波蘭表達式求值

求逆波蘭表達式的值。

在逆波蘭表達法中,其有效的運算符號包括 +-*/ 。每個運算對象可以是整數,也可以是另一個逆波蘭計數表達。

您在真實的面試中是否遇到過這個題? 
Yes
樣例
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
說明
標籤 Expand  

相關題目 Expand  

Timer Expand 


解題思路:
可以使用棧
public class Solution {
    /**
     * @param tokens The Reverse Polish Notation
     * @return the value
     */
    public int evalRPN(String[] tokens) {
        // Write your code here
    	if(tokens==null||tokens.length==0) 
    		return 0;
    	Stack<Integer> stack = new Stack<>();
    	for(String str:tokens){
    		if("+".equals(str)){
    			int a =stack.pop();
    			int b = stack.pop();
    			int c = b+a;
    			stack.add(c);
    		}else if("-".equals(str)){
    			int a =stack.pop();
    			int b = stack.pop();
    			int c = b-a;
    			stack.add(c);
    		}else if("*".equals(str)){
    			int a =stack.pop();
    			int b = stack.pop();
    			int c = b*a;
    			stack.add(c);
    		}else if("/".equals(str)){
    			int a =stack.pop();
    			int b = stack.pop();
    			int c = b/a;
    			stack.add(c);
    		}else{
    			stack.add(Integer.valueOf(str));
    		}
    	}
    	return stack.pop();    	    	
        
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章