Evaluate the value of an arithmetic expression inreverse Polish Notation.
Valid operators is +
, -
, *
, /
. Each operand is an integer or another expression.
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Public classSolution {/** * @paramtokens the Reverse Polish Notation *@returnThe value*/ Public intEVALRPN (string[] tokens) {//Write Your code here if(Tokens = =NULL|| Tokens.length = = 0) return0; Stack<Integer> stack =NewStack<integer>(); for(inti = 0; i < tokens.length; i++){ if(!isOp (Tokens[i])) {Stack.push (Integer.parseint (tokens[i])); } Else{ intnum2 =Stack.pop (); intNUM1 =Stack.pop (); if(Tokens[i].equals ("+")) Stack.push (Num1+num2); Else if(Tokens[i].equals ("-")) Stack.push (Num1-num2); Else if(Tokens[i].equals ("*")) Stack.push (Num1*num2); ElseStack.push (Num1/num2); } } returnStack.pop (); } Public BooleanisOp (String str) {return(Str.equals ("+") | | str.equals ("-") | | str.equals ("*") | | str.equals ("/")); }}
Lintcode-medium-evaluate Reverse Polish Notation