1.题目
Infix to Postfix
Write a function to convert a infix string into a postfix string. For this quiz, you may assume the string only contains numbers and the following operator: +, -, *, /, (, ).
将中缀表达式 ‘2-(5+3*2+1)/3’ 转换成后缀表达式。
2.解题思路
从左到右扫描表达式:
(1)当前扫描到的是数字,直接添加到输出字符穿out中;
(2)当前扫描到的是符号,将栈内所有与当前符号相同或相等优先级的符号出栈并添加到输出字符串out中;再将当前符号入栈。
(3)当前扫描到的是 ‘(’ ,直接入栈;
(4)当前扫描到的是 ‘)’ ,一直出栈并把出栈的元素添加到输出字符串out中直到遇到 ‘)’ ;再将 ‘(’ 出栈(注意:但千万不要将 ‘(’ 添加到输出字符串中了)。
(5)当表达式全部扫描完毕,将所有元素出栈并添加到输出字符串out中。
3.code:
- 小技巧:用如下代码防止表达式中混有空格。
infix = ‘’.join([c for c in infix if c != ’ '])
def infix_to_postfix(infix: str) -> str:
# Remove all white space
infix = ''.join([c for c in infix if c != ' '])
stk = []
out = ''
for c in infix:
if c.isdigit(): # if c is an operand
out += c
elif c == '(':
stk.append(c)
elif c == ')': # pop until '('
while stk[-1] != '(':
out += stk.pop()
stk.pop()
else: # if c is an operator
high_pre_op = '*/+-' if c in "+-" else '*/'
while stk and stk[-1] in high_pre_op:
out += stk.pop()
stk.append(c)
while stk:
out += stk.pop()
return out
# Call the above function
infix_to_postfix('2 +( 5 + 3 * 2 + 1 ) / 3')
result:
'2532*+1+3/+'