算法4练习 补全左括号问题--双栈

问题描述

输入例如 1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) ),程序应该输出 ( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) )

思路

此题思路跟计算式中序变后序相似,采用双栈的做法,数字一个栈(String栈),运算符一个栈(Character栈),读到数字,则压入数字栈,读到运算符,则压入运算符栈。
读到右括号时:
1.从数字栈中弹出两个操作数字
2.从运算符栈弹出一个运算符
3.认为添加左括号,组成新的表达式,整体看作一个数字并压入数字栈
循环至最后一个右括号

程序结束时,数字栈的栈顶即为所需表达式

代码

```
public static  void CompleteLeftParenthesis() {
    String str = StdIn.readLine();
    Stack<Character> operation = new Stack<Character>();
    Stack<String> formula = new Stack<String>();
    for(int i = 0; i < str.length(); i++) {
        char temp = str.charAt(i);
        if(Character.isDigit(temp)){
            formula.push(Character.toString(temp));
        } else if(temp == '+' || temp == '-' || temp == '*' || temp == '/') {
            operation.push(temp);
        } else if(temp == ')') {
            String A = formula.pop();
            String B = formula.pop();
            char C = operation.pop();
            String newFormula = "("+B+Character.toString(C)+A+")";
            formula.push(newFormula);
        } else {
            continue;  //忽略掉表达式中的空格等字符
        }
    }
    System.out.println(formula.peek());
}
```
posted @ 2019-09-04 09:24  dwwzone  阅读(123)  评论(0编辑  收藏  举报