Remove redundant parentheses from an arithmetic expression

后端 未结 7 1284
陌清茗
陌清茗 2020-12-13 10:27

This is an interview question, for which I did not find any satisfactory answers on stackoverflow or outside. Problem statement:

Given an arithmetic

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 11:21

    1. Push one empty item in the stack
    2. Scan the token list

      2.1 if the token is operand, ignore.

      2.2 if the token is operator, records the operator in the left_op, if min_op is nil, set the min_op = this operator, if the min_op is not nil, compare the min_op with this operator, set min_op as one of the two operators with less priority.

      2.3 if the token is left parenthese, push one item in the stack, with left_pa = position of the parenthesis.

      2.4 if the token is right parenthesis:

      2.4.1 we have the pair of the parentheses(left_pa and the right parenthesis)

      2.4.2 pop the item

      2.4.3 pre-read next token, if it is an operator, set it as right operator

      2.4.4 compare min_op of the item with left_op and right operator (if any of them exists), we can easily get to know if the pair of the parentheses is redundant, and output it(if the min_op < any of left_op and right operator, the parentheses are necessary, if min_op = left_op, the parentheses are necessary, otherwise redundant)

      2.4.5 if there is no left_op and no right operator(which also means min_op = nil) and the stack is not empty, set the min_op of top item as the min_op of the popped-up item examples

提交回复
热议问题