zoukankan      html  css  js  c++  java
  • 算法(Algorithms)第4版 练习 1.3.9

    主要思路:

    用Dijkstra的双栈算法。

    遇到数字则压入数字栈中(String)。

    遇到运算符则压入运算符栈中(String)。

    遇到右括号时,从数字栈和运算法栈中弹出相应的元素,生成相应的运算表达式(添加左括号)。

    再次压入数字栈中(String)。

    最后从数字栈中弹出最终的运算表达式。

    方法实现:

    //1.3.9
    //only support +-*/ sqrt operator
    package com.qiusongde;
    
    import edu.princeton.cs.algs4.StdIn;
    import edu.princeton.cs.algs4.StdOut;
    
    public class AddLeftParentheses {
    
        public static void main(String[] args) {
            
            Stack<String> ops = new Stack<String>();
            Stack<String> vals = new Stack<String>();
            
            while(!StdIn.isEmpty()) {
                String s = StdIn.readString();
                
                if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") || s.equals("sqrt")) {
                    ops.push(s);
                }
                else if(s.equals(")")) {
                    String op = ops.pop();//operator
                    String v = vals.pop();//value
                    
                    if(op.equals("+") || op.equals("-") || op.equals("*") || op.equals("/")) {
                        String subexpression = "( " + vals.pop() + " " + op  + " " + v + " )";
                        vals.push(subexpression);
                    }
                    
                    if(op.equals("sqrt")) {
                        String subexpression = op + " ( " + v + " )";
                        vals.push(subexpression);
                    }
                    
                }
                else {
                    vals.push(s);
                }
                
            }
            
            StdOut.println(vals.pop());
            
        }
    
    }

    测试结果:

     

  • 相关阅读:
    .NET委托与事件文章收集
    WCF简介
    设计模式之单例模式
    设计模式之工厂模式
    设计模式之简单工厂模式
    Jquery中bind和live的区别
    C#性能优化实践
    蒋金楠How ASP.NET MVC Works?[持续更新中…]
    按指定质量保存图片
    .net 获取网站根目录总结
  • 原文地址:https://www.cnblogs.com/songdechiu/p/6513904.html
Copyright © 2011-2022 走看看