-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefix_to_postfix_conversion.py
46 lines (33 loc) · 1.19 KB
/
prefix_to_postfix_conversion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
You are given a string that represents the prefix form of a valid mathematical expression. Convert it to its postfix form.
Example:
Input:
*-A/BC-/AKL
Output:
ABC/-AK/L-*
Explanation:
The above output is its valid postfix form.
Your Task:
Complete the function preToPost(string pre_exp), which takes a prefix string as input and returns its postfix form.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
3<=pre_exp.length()<=100
"""
class Solution:
def preToPost(self, pre_exp):
# Code here
stack = []
# Iterate through the prefix expression in reverse order
for char in pre_exp[::-1]:
# If the character is an operand, push it to the stack
if char.isalpha():
stack.append(char)
# If the character is an operator, pop two operands from the stack,
# concatenate them with the operator, and push the result back to the stack
else:
op1 = stack.pop()
op2 = stack.pop()
stack.append(op1 + op2 + char)
# The final postfix expression is at the top of the stack
return stack.pop()