Evaluate Reverse Polish Notation
Problem:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators is + , - , * , / . Each operand is an integer or another expression.
Ideas:
Classic Application of Stacks
My Code:
Public classSolution { Public intEVALRPN (string[] tokens) {if(Tokens = =NULL|| Tokens.length = = 0)return0; Stack<Integer> stack =NewStack<integer>(); for(inti = 0; i < tokens.length; i++) {String str=Tokens[i]; if(Isoperator (str)) {intone =Stack.pop (); intboth =Stack.pop (); Stack.push (GetResult (one, one, str)); } Else{stack.push (integer.valueof (str)); } } returnStack.isempty ()? 0: Stack.pop (); } Public intGetResult (intOneintBoth , String str) { Switch(str) { Case"+":returnOne +both ; Case"-":returnOne-both ; Case"*":returnOne *both ; Case"/":returnOne/both ; } return0; } Public Booleanisoperator (String str) {if(Str.equals ("+") | | str.equals ("-") | | str.equals ("*") | | str.equals ("/"))return true; return false; }}View Code
Evaluate Reverse Polish Notation