![]() |
VOOZH | about |
Given a string s representing an infix expression ("operand1 operator operand2" ), Convert it into its prefix notation ("operator operand1 operand2").
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: /*a+bcd
Explanation: The infix 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 *a+bc. Finally, divide this result by d, so it becomes /*a+bcd.
Table of Content
The idea is to scan the expression from right to left, directly placing operands (a, b, cā¦) into the result as they appear. Operators (+, -, *, /, ^) are handled using a stack so that precedence and associativity are maintained.
How to Maintain Precedence and Associativity?
To maintain precedence and associativity, when a new operator appears, compare it with the operator on 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 right-associative (^). Left-associative operators (+, -, *, /) do not cause a pop. Push the new operator onto the stack. For parentheses (when scanning right to left), push ')' onto the stack, and when '(' is encountered, pop operators until a ')' is found.
At the end, pop all remaining operators from the stack and add them to the result. Finally, reverse the result to obtain the correct prefix expression.
/*a+bcd
To convert an infix expression to prefix, we make use of the infix-to-postfix method with a small modification.
Note: Prefix = reverse( postfix( reverse(infix) ) )
Illustration:
/*a+bcd