![]() |
VOOZH | about |
Given a string s representing an infix expression ("operand1 operator operand2" ), Convert it into its postfix notation ("operand1 operand2 operator").
Note: The precedence order is as follows: (^) has the highest precedence and is evaluated from right to left, (* and /) come next with left to right associativity, and (+ and -) have the lowest precedence with left to right associativity.
Examples:
Input: s = "a*(b+c)/d"
Output: abc+*d/
Explanation: The expression is a * (b + c) / d. First, inside the brackets, b + c becomes bc+. Now the expression looks like a * (bc+) / d. Next, multiply a with (bc+), so it becomes abc+* . Finally, divide this result by d, so it becomes abc+*d/.Input: s = "a+b*c+d"
Output: abc*+d+
Explanation: The expression a + b * c + d is converted by first doing b * c ā bc*, then adding a ā abc*+, and finally adding d ā abc*+d+.
The idea is to scan the expression from left to right, directly placing operands (a, b, cā¦) in the same order as they appear into the result and place operators (+, -, *, /, ^) after their operands. Operators are handled using a stack so that precedence and associativity are maintained.
How to Maintain Precedence and Associativity?
To maintain operator precedence and associativity, compare each new operator with the top of the stack. Pop operators from the stack if they have higher precedence, or if they have equal precedence and the new operator is left-associative (+, -, *, /). If the new operator is right-associative (^), leave the stack operators in place. Push the new operator onto the stack. Parentheses are handled specially: '(' is pushed onto the stack, and when ')' is encountered, operators are popped until a matching '(' is found.
abc+*d/