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
棧的基本應用之一。
public int evalRPN(String[] tokens) {
        Stack<String> s = new Stack<String>();
		for(int i = 0 ; i < tokens.length ; ++i){
			if(tokens[i].equals("+")){
				int b = Integer.parseInt(s.pop());
				int a = Integer.parseInt(s.pop());
				s.push(String.valueOf(a+b));
			}else if(tokens[i].equals("-")){
				int b = Integer.parseInt(s.pop());
				int a = Integer.parseInt(s.pop());
				s.push(String.valueOf(a-b));
			}else if(tokens[i].equals("*")){
				int b = Integer.parseInt(s.pop());
				int a = Integer.parseInt(s.pop());
				s.push(String.valueOf(a*b));
			}else if(tokens[i].equals("/")){
				int b = Integer.parseInt(s.pop());
				int a = Integer.parseInt(s.pop());
				s.push(String.valueOf(a/b));
			}else{
				s.push(tokens[i]);
			}
		}
		return Integer.parseInt(s.pop());
    }



Submission Result: Accepted






發佈了24 篇原創文章 · 獲贊 10 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章