Inverse Polish: Reverse Polish Notation,rpn, also known as a suffix expression, writes an operator after the operand
Data structure: Two stacks of S1 and S2. S1 temporary storage operator, S2 stores the final result.
Algorithm:
(1) If the character being taken is an operand, the complete calculation is analyzed, and the operand is fed directly into the S2 stack.
(2) If the removed character is an operator, the operator is compared to the top element of the S1 stack, if the operator priority is greater than the S1 stack top operator priority, then the operator into the S1 stack, otherwise, the stack top operator of the S1 stack pops up into the S2 stack, The operator is fed into the S1 stack until the S1 stack top operator is below (not equal to) the operator priority.
(3) If the character being removed is "(", it is fed directly to the top of the S1 stack.)
(4) If the character that is removed is ")", then the "(" operator from the top of the S1 stack will be sent to the S2 stack, which is then discarded.
(5) Repeat the 1~4 step above until all the input characters are processed
(6) Finally, all the operators in the S1 stack, one by one, are fed into the S2 stack.
classSolution { Public: stringReversepolishnotation (stringEXP) {//Assuming that the operands are all a single numbermap<Char,int>oppriority; oppriority['+'] =1; oppriority['-'] =1; oppriority['*'] =2; oppriority['/'] =2; oppriority['('] =0; Stack rpnstack; Stack tmpstack; for(inti =0; I < exp.size (); i++){ if(Exp[i] <='9'&& Exp[i] >='0') Rpnstack.push (Exp[i]); Else if(exp[i]==')'){ while(Tmpstack.top ()! ='(') {Rpnstack.push (Tmpstack.top ()); Tmpstack.pop (); } tmpstack.pop (); } Else if(exp[i]=='('||tmpstack.empty ()) Tmpstack.push (Exp[i]); Else{ while(!tmpstack.empty () && oppriority[tmpstack.top ()] >Oppriority[exp[i]]) {Rpnstack.push (Tmpstack.top ()); Tmpstack.pop (); } tmpstack.push (Exp[i]); } } while(!Tmpstack.empty ()) {Rpnstack.push (Tmpstack.top ()); Tmpstack.pop (); } stringRET =""; while(!Rpnstack.empty ()) {ret= Rpnstack.top () +ret; Rpnstack.pop (); } returnret; }};
Convert infix to inverted Polish (stack)