添加缺少左括号入式括号

2023-09-11 02:19:12 作者:花落微凉梦清幽

我是pretty的停留在找到一个给定的问题得到妥善解决,一直在寻找一些想法在互联网上。没有能找到任何

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.

问题是:写一个程序,它从标准输入的前pression没有留下括号并打印相当于缀EX pression插入了括号

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.

由于EX pression: 1 + 2)* 3 - 4)* 5 - 6))) 输出:((1 + 2)*((3 - 4)*(5 - 6)))

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?

推荐答案

我觉得,我们的目标是假设你只插EX pressions,而不是孤独的数字。

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

抓住下一个标记,这是) 现在就堆栈的前三名和夹心它的括号(1 + 2)之间,将其放回栈为一体EX pression上。

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)

和再

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

我们再创括号并再次抢前3名从堆栈,插推背

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

(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)

和再...

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

没有更多的投入,所以这是我们的答案

no more input, so this is our answer