zoukankan      html  css  js  c++  java
  • Algs4-1.3.4用Stack检查括号是否配对

    1.3.4编写现代一个Stack的用例Parentheses,从标准输入中读取一个文本流并使用栈判定其中的括号是否配对完整。
    例如,对于[()]{}{[()()]()}程序应该打印true,对于[(])则打印false。
    答:
    上一次发布的code没有考虑栈为空时读入右括号的情形。
    算法如下:
    置结果为true
    不断的读入数据,直到读入空或结果为false时结束读入
    1)读入左括时入栈
    2)读入右括号时
        2.1)如果栈为空结置置为false
        2.2)如果栈有内容,弹出一次,弹出的值如果是与右括号不同类型的左括号,置结果为false
    结束读入数据
    3)栈为空并且结果为ture,那么为结果为true,其他情况下结果为false.
    public  class Parentheses
    {
        public static void main(String[] args)
        {
            boolean result=true;
            Stack<String> s=new Stack<String>();
            while(!StdIn.isEmpty() && result)
            {
                String item=StdIn.readString();
              if (item.equals("(") || item.equals("[") || item.equals("{"))
                 s.push(item);
              else if(item.equals(")"))
                   if(s.isEmpty())
                       result=false;
                   else
                      result=s.pop().equals("(");
              else if(item.equals("]"))
                   if(s.isEmpty())
                       result=false;
                   else
                       result=s.pop().equals("[");
             else if(item.equals("}"))
                   if(s.isEmpty())
                       result=false;
                   else
                      result=s.pop().equals("{");
            }//end while
            result=result && s.isEmpty();
            StdOut.println(result);
        }//end main
    }//end class   

  • 相关阅读:
    测试如何发挥更大的价值?聊聊测试左移和右移
    Cocos Creator性能调优
    跨域问题产生的原因和解决方法
    tornado部署
    tonado
    MySQL binlog
    grpc
    nextjs中的懒加载
    前端低代码-少写代码实现灵活需求
    MySQL中的锁
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9849295.html
Copyright © 2011-2022 走看看