First, the original question
Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators is +
, -
, *
, /
. Each operand is an integer or another expression.
Some Examples:
["2", "1", "+", "3", "*")--((2 + 1) (3)-9 ["4", "", "5", "/", "+"], 4 + (13/5))
Second, analysis
The analysis here quoted Baidu Library for the inverse Polish expression calculation method.
"It has the advantage of using only two simple operations, both in the stack and out of the stack to take care of any ordinary expression operation." The operation is as follows: If the current character is a variable or a number, then the stack, if it is an operator, the top two elements of the stack pop up for the corresponding operation, the result is then into the stack, and finally when the expression scan, the stack is the result. ”
Third, code (JAVA)
Import Java.util.stack;public class reversepolishnotation {stack<string> stack =new stack ();p ublic int Evalrpn ( String[] Tokens) {if (tokens.length==0) return 0;int temp1,temp2,temp3;temp1=temp2=temp3=0; for (int i=0;i<tokens.length;i++) {if (Tokens[i].equals ("+") | | Tokens[i].equals ("-") | | Tokens[i].equals ("*") | | Tokens[i].equals ("/")) {if (tokens.length==1) return 0; Temp1=integer.parseint (Stack.peek ()); Stack.pop (); Temp2=integer.parseint (Stack.peek ()); Stack.pop (); if (tokens[i].equals ("+")) {temp3=temp1+temp2; Stack.push (integer.tostring (Temp3));//The result of the calculation will also be in the stack} else if (Tokens[i].equals ("*")) {temp3=temp1*temp2; Stack.push (integer.tostring (Temp3)); } else if (Tokens[i].equals ("/")) {temp3=temp2/temp1; Note the order of Temp2 and Temp1 Stack.push (integer.tostring (Temp3)); } else if (Tokens[i].equals ("-")) {temp3=temp2-temp1; Stack.push (integer.tostring (Temp3)); }} else{Temp3=integer.parseint (tokeNs[i]);//For input similar to {"18"}, both (s.length==1) && (S[0] represent the number) Stack.push (Tokens[i]); }}return Temp3; }}
"Leetcode" Evaluate Reverse Polish notation Answer