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))
Inverse Polish expression is to put the operand in front, put the operator behind a notation, we can see that the first occurrence of the operator, before it must have two numbers, when the operator and the previous two numbers after the completion of the operation from the original array is deleted, to get a new number inserted into the original position, continue to do the same operation Until the entire array becomes a number. So according to this idea wrote the code as follows:
/** * Time Limit exceeded*/classSolution { Public: intEVALRPN (vector<string> &tokens) { if(tokens.size () = =1)returnAtoi (tokens[0].c_str ()); intn =tokens.size (); intCur =0, res =0; while(Tokens.size ()! =1) {n=tokens.size (); Cur=0; while(Tokens[cur]! ="+"&& Tokens[cur]! ="-"&& Tokens[cur]! ="*"&& Tokens[cur]! ="/") ++cur; intA = Atoi (Tokens[cur-2].c_str ()); intb = Atoi (Tokens[cur-1].c_str ()); if(Tokens[cur] = ="+") res = a +b; if(Tokens[cur] = ="-") res = A-b; if(Tokens[cur] = ="*") Res = A *b; if(Tokens[cur] = ="/") res = A/b; Tokens.insert (Tokens.begin ()+ cur +1, To_string (res)); for(inti = cur; I >= cur-2; --i) {tokens.erase (Tokens.begin ()+i); } } returnRes; }};
But get OJ on the test, found that there will be time Limit exceeded error, helpless had to search the answer on the Internet, found that we are all done with the stack. Think about it, this problem should be the perfect application of the stack ah, from the past to iterate over the array, encountered the number is pressed into the stack, encountered the symbol, then the top of the stack of two numbers out of the operation, the results are then pressed into the stack, until the complete number of the stack, the top number is the final answer. The code is as follows:
classSolution { Public: intEVALRPN (vector<string> &tokens) { if(tokens.size () = =1)returnAtoi (tokens[0].c_str ()); Stack<int>s; for(inti =0; I < tokens.size (); ++i) {if(Tokens[i]! ="+"&& Tokens[i]! ="-"&& Tokens[i]! ="*"&& Tokens[i]! ="/")
{S.push (Atoi (Tokens[i].c_str ())); } Else { intm =S.top (); S.pop (); intn =S.top (); S.pop (); if(Tokens[i] = ="+") S.push (n +m); if(Tokens[i] = ="-") S.push (N-m); if(Tokens[i] = ="*") S.push (n *m); if(Tokens[i] = ="/") S.push (N/m); } } returnS.top (); }};
[Leetcode] Evaluate Reverse Polish Notation calculation inverse Polish expression