问题
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