First, the problem description
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 problem is actually a suffix expression of the calculation, the implementation of this topic mainly has the following points:
1. How to read the operands and operators in a string array and distinguish them.
2. When the operand is read out, put the operand into the stack
3. When the operator is read out, two elements are removed from the stack and evaluated with this operator, and the result of the calculation is placed in the stack
PackageCom.edu.leetcode;ImportJava.util.Stack; Public classevaluatereversepolishnotation { Public intEVALRPN (string[] tokens) {Stack<Integer> stack =NewStack<>(); intresult = 0; for(inti = 0; i < tokens.length; i++) { Charc = Tokens[i].charat (0);//take out the first element of a string if(Tokens[i].length ()!=1| | ' 0 ' <= c && c <= ' 9 ') {//the criterion for determining the operand: 1, when the length of the string is greater than 2 o'clock, it must be a number, 2, when the length is 1 o'clock, if the first is an integer;Stack.push (integer.valueof (Tokens[i]). Intvalue ()); } Else { intTwonumber = Stack.pop ();//the top element of the stack is taken as the second operand intOnenumber = Stack.pop ();//and remove the top element of the stack first operand Switch(c) {//calculates the result based on the operand Case‘*‘: Result= Onenumber *Twonumber; Break; Case+: Result= Onenumber +Twonumber; Break; Case‘-‘: Result= Onenumber-Twonumber; Break; Case‘/‘: if(Twonumber! = 0) {result= Onenumber/Twonumber; Break; } Else{System.out.println ("\ndivided by 0!"); Stack.clear (); }} stack.push (Result); Put the result in the stack}}returnStack.pop (); } Public Static voidMain (string[] args) {//TODO auto-generated Method StubString[] string = {"0", "3", "/"}; Evaluatereversepolishnotation ERPN=Newevaluatereversepolishnotation (); ints =ERPN.EVALRPN (string); System.out.println (s); }}
"Leetcode" Evaluate Reverse Polish Notation JAVA