zoukankan      html  css  js  c++  java
  • 算法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());
    }
    ```
    
  • 相关阅读:
    mybatis_7分页查询
    mybatis_6日志工厂
    mybatis_5解决属性名和字段名不一致的问题(resultMap)
    mybatis_4配置解析
    mybatis_3CRUD操作
    ARM C函数调用堆栈入栈顺序
    syscall SYSCALL_DEFINE*()实现
    ko kallsyms
    elf文件结构解析
    ko module加载flow
  • 原文地址:https://www.cnblogs.com/dwwzone/p/12859258.html
Copyright © 2011-2022 走看看