1. 程式人生 > >leetcode-Evaluate the value of an arithmetic expression in Reverse Polish Notation

leetcode-Evaluate the value of an arithmetic expression in Reverse Polish Notation

ret i++ value reverse alua style 執行 掃描 span

leetcode 逆波蘭式求解

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.Stack; public class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<Integer>(); int tmp; for(int i = 0; i<tokens.length; i++){ if("+".equals(tokens[i])){ int a = stack.pop();
int b = stack.pop(); stack.add(b+a); } else if("-".equals(tokens[i])){ int a = stack.pop(); int b = stack.pop(); stack.add(b-a); } else if("*".equals(tokens[i])){ int a = stack.pop();
int b = stack.pop(); stack.add(b*a); } else if("/".equals(tokens[i])){ int a = stack.pop(); int b = stack.pop(); stack.add(b/a); } else{ stack.add(Integer.parseInt(tokens[i])); } } return stack.pop(); } }

根據你波蘭式求值。看到逆波蘭式可以想到棧,掃描表達式,遇到數字則將數字入棧,遇到運算符,時,則從棧頂彈出兩個元素,後彈出的元素在運算符的左邊,先彈出的元素在元素符的右邊,執行運算,將結果入棧。掃描結束後,棧中的元素只剩下一個,即逆波蘭式的值

leetcode-Evaluate the value of an arithmetic expression in Reverse Polish Notation