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   

  • 相关阅读:
    git httphttpsgit免密设置记住用户名和密码的方法
    WPF部署问题 解决:The application requires that the assembly...be installed in the GAC
    reporting service & wpf
    洪应明《菜根谭》
    焦郁《白云向空尽》
    .net 裁剪图片
    js 本地预览图片和得到图片实际大小
    display: -webkit-box; 做个小小试验
    C# json
    宽域POST提交数据
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9849295.html
Copyright © 2011-2022 走看看