Add missing left parentheses into equation [closed]

冷暖自知 提交于 2019-12-08 01:34:36

问题


I'm pretty stuck in finding a proper solution for a given problem, been looking for some ideas over the internet. Wasn't be able to find any.

Problem is: writing a program that takes from the standard input an expression without left parentheses and prints the equivalent infix expression with the parentheses inserted.

Given expression: 1 + 2) * 3 - 4)* 5 - 6)))
Output: ((1 + 2) * ((3 - 4) * (5 - 6)))

What can be the best approach to solve this problem?


回答1:


I think that the goal is assuming that you only parenthesize expressions, not lone numbers.

So you'll want to grab each token and toss them on a stack

2
+
1

grab the next token, which is ) now take the top three of the stack and sandwich it between those parens ( 1 + 2 ), put it back on the stack as one expression.

next push the stack looks like this

4
-
3
*
(1 + 2)

pull out the top three and put it back on the stack parenthesized (3-4) * (1+2)

and again

6
-
5
*
(3-4)
*
(1+2)

we hit another paren and grab the top 3 from the stack again, parenthesize and push back

(5-6)
*
(3-4)
*
(1+2)

We grab another paren, grab the top 3 from the stack again, parenthesize and push back

((3-4)*(5-6))
*
(1+2)

and again...

((1 + 2) * ((3 - 4) * (5 - 6)))

no more input, so this is our answer



来源:https://stackoverflow.com/questions/19062718/add-missing-left-parentheses-into-equation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!