Update Leetcode to solve Java answers on a regular basis.
Choose a topic using pick one.
Test instructions Returns the result of a computed sequence given a tree-like operator suffix.
["2", "1", "+", "3", "*"], ((2 + 1) * 3), 9
["4", "+", "5", "/", "+"], (4 + (13/5)), 6
We can see that the last digit is calculated first, the stack is used to store the number, the operator is out of the stack operation, and the result of the operation is put into the stack again, the end of the operation, the stack is left a value of the calculation results.
The code is as follows:
1 Public classSolution {2 Public intEVALRPN (string[] tokens) {3stack<integer> stack =NewStack ();4 for(inti = 0; i < tokens.length; i++){5 if(Tokens[i].charat (Tokens[i].length ()-1) >= ' 0 ' && Tokens[i].charat (Tokens[i].length ()-1) <= ' 9 ')6 Stack.push (Integer.parseint (tokens[i));7 Else{8 intnum2 =Stack.pop ();9 intNUM1 =Stack.pop ();Ten Stack.push (Calculate (NUM1, num2, Tokens[i])); One } A } - returnStack.pop (); - } the - Public intCalculateintNUM1,intnum2, String str) { - if(Str.equals ("+")) - returnNUM1 +num2; + Else if(Str.equals ("-")) - returnNUM1-num2; + Else if(Str.equals ("*")) A returnNUM1 *num2; at Else - returnNUM1/num2; - } -}
Leetcode 150. Evaluate Reverse Polish Notation