编写一道程序,从标准输入得到一个缺少左括号的表达式并打印出补全括号之后的中序表达式。例如,给定输入:
1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )
你的程序应该输出:
1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )
你的程序应该输出:
((1 + 2) * ((3 - 4) * (5 - 6)))
/**
* 算法思路:(1)将操作符号存入ops栈中(2)将操作数存入vals栈中
* (3)如果遇到右括号”)“,则从vals栈中弹出两个操作数,从ops栈
* 中弹出一个操作符号进行相应的连接,将连接后的newString压入vals
* 栈中。
*/
public class Test1 {
public static String reConnect(String[] args){
Stack<String> ops = new Stack<>();
Stack<String> vals = new Stack<>();
for (String s : args) {
if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/")){
ops.push(s);
}else if(s.equals(")")){
String firstString=vals.pop();
String secondString=vals.pop();
String newString ="("+secondString+ops.pop()+firstString+")";
vals.push(newString);
}else{
vals.push(s);
}
}
return vals.pop();
}
}