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))
Given a string array, the data is a suffix expression that evaluates the value of the expression.
Problem-solving ideas: With the stack to save the operand, encountered the number on the stack, encountered the operator from the stack to take out two elements of the operation and then into the stack, the last stack only one element is the result. It's easier to do this without parentheses, directly on the code.
StaticMap<string, integer> op =NewHashmap<>(); Static{op.put ("+", 1); Op.put ("-", 2); Op.put ("*", 3); Op.put ("/", 4); } Public intEVALRPN (string[] tokens) {if(Tokens = =NULL|| Tokens.length = = 0) { return0; } Stack<Integer> nums =NewStack<>(); for(String s:tokens) {if(Op.get (s)! =NULL) { intFA =Nums.pop (); intFB =Nums.pop (); if(Op.get (s) = = 1) {Nums.push (FB+FA); } Else if(Op.get (s) = = 2) {Nums.push (FB-FA); } Else if(Op.get (s) = = 3) {Nums.push (FB*FA); } Else{Nums.push (FB/FA); } } Else{Nums.push (integer.valueof (s)); } } returnNums.peek (); }
Evaluate Reverse Polish Notation--leetcode