将缺少的左括号添加到方程中 [英] Add missing left parentheses into equation
问题描述
我很难找到一个适当的解决方案给定的问题,一直在寻找一些想法在互联网上。找不到任何。
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.
给定表达式: 1 + 2)* 3 - 4)* 5 - 6) br>
输出:((1 + 2)*((3 - 4)*(5-6)))
解决这个问题的最佳方法是什么?
What can be the best approach to solve this problem?
推荐答案
我认为目标是假设
因此,您需要抓取每个令牌并将它们折叠到一个堆栈上
So you'll want to grab each token and toss them on a stack
2
+
1
$ b b
抓取下一个标记,这是)
现在取堆栈的顶部三个,并将它们夹在那些括号(1 + 2)之间,将其作为一个表达式放回堆栈。
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)
三把它放回栈上括号
(3-4)
*
(1 + 2)
pull out the top three and put it back on the stack parenthesized (3-4) * (1+2)
/ p>
and again
6
-
5
*
(3-4)
*
(1+2)
(5-6)
*
(3-4)
*
(1+2)
从堆栈中再次抓取前3名,括号并推回
We grab another paren, grab the top 3 from the stack again, parenthesize and push back
((3-4)*(5-6))
*
(1+2)
p>
and again...
((1 + 2) * ((3 - 4) * (5 - 6)))
没有更多的输入,所以这是我们的答案
no more input, so this is our answer
这篇关于将缺少的左括号添加到方程中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!