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))
is to reverse the result of the Polish expression (subsequent traversal).
1, direct solution, very slow
Public classSolution { Public intEVALRPN (string[] tokens) {intLen =tokens.length; if(len = = 0) return0; for(inti = 0; i < Len; i + + ){ if(Tokens[i].equals ("+") Helper (Tokens,i,1); Else if(Tokens[i].equals ("-") Helper (Tokens,i,2); Else if(Tokens[i].equals ("*") Helper (Tokens,i,3); Else if(Tokens[i].equals ("/") Helper (Tokens,i,4); } returnInteger.valueof (tokens[0]); } Public voidHelper (string[] tokens,intPosinttype) { intPOS1 = -1,pos2 = 0 ; Tokens[pos]=NULL; while(POS >= 0 ){ if(Tokens[pos]! =NULL){ if(POS1 = =-1) POS1=POS; Else{Pos2=POS; Break; }} POS--; } intNUM1 =integer.valueof (TOKENS[POS1]); intnum2 =integer.valueof (Tokens[pos2]); if(Type = = 1) {Tokens[pos2]= String.valueof (num1+num2); }Else if(Type = = 2) {Tokens[pos2]= String.valueof (num2-NUM1); }Else if(Type = = 3) {Tokens[pos2]= String.valueof (num2*NUM1); }Else if(Type = = 4) {Tokens[pos2]= String.valueof (num2/NUM1); } TOKENS[POS1]=NULL; } }
2, the use of stacks, very simple.
Public classSolution { Public intEVALRPN (string[] tokens) {intLen =tokens.length; if(len = = 0) return0; Stack<Integer> stack =NewStack<integer>(); for(inti = 0; i < Len; i + + ){ if(Tokens[i].equals ("+") ){ intNUM1 =Stack.pop (); intnum2 =Stack.pop (); Stack.push (NUM1+num2); } Else if(Tokens[i].equals ("-") ){ intNUM1 =Stack.pop (); intnum2 =Stack.pop (); Stack.push (num2-NUM1); } Else if(Tokens[i].equals ("*") ){ intNUM1 =Stack.pop (); intnum2 =Stack.pop (); Stack.push (NUM1*num2); } Else if(Tokens[i].equals ("/") ){ intNUM1 =Stack.pop (); intnum2 =Stack.pop (); Stack.push (num2/+NUM1); }Else{Stack.push (integer.valueof (tokens[i])); } } returnStack.pop (); } }
Leetcode 150. Evaluate Reverse Polish Notation------java