zoukankan      html  css  js  c++  java
  • 爪哇国新游记之十九----使用Stack检查数字表达式中括号的匹配性

    /**
     * 辅助类
     * 用于记载字符和位置
     *
     */
    class CharPos{
        char c;
        int pos;
        
        public CharPos(char c,int pos){
            this.c=c;
            this.pos=pos;
        }
    }
    
    /**
     * 括号检查类
     *
     */
    public class BracketChecker{
        /**
         * 检查函数
         * @param str
         * @return
         * @throws Exception
         */
        public static boolean check(String str) throws Exception{
            int length=str.length();
            Stack<CharPos> stack=new Stack<CharPos>(CharPos.class,length);
            
            for(int i=0;i<length;i++){
                char ch=str.charAt(i);
                
                if(ch=='{' || ch=='[' || ch=='('){
                    stack.push(new CharPos(ch,i));
                }else if(ch==')' || ch==']' || ch=='}'){
                    try{
                        CharPos poped=stack.pop();
                        
                        if( (ch==')' && poped.c !='(') || (ch==']' && poped.c !='[') || (ch=='}' && poped.c !='{')){
                            throw new Exception("位于第"+(i+1)+"位的字符"+ch+"没有对应的匹配项");
                        }
                    }catch(java.lang.ArrayIndexOutOfBoundsException e){
                        throw new Exception("位于第"+(i+1)+"位的字符"+ch+"没有对应的匹配项");
                    }
                }
            }
            
            StringBuilder sb=new StringBuilder();
            while(stack.isEmpty()==false){
                CharPos poped=stack.pop();
                sb.append("位于第"+(poped.pos+1)+"位的字符"+poped.c+"没有对应的匹配项,");
            }
            if(sb.length()>0){
                throw new Exception(sb.toString());
            }
            
            return true;
        }
        
        public static void main(String[] args) throws Exception{
            String[] arr={"5+2*(3+3)","{[(2+4)*8]/6}","[()]}","{[(]}","{[](","(((((())))))","((([((())))))","[[[[[]]]]]"};
            
            for(String str:arr){
                try{
                    boolean isOk=BracketChecker.check(str);
                    if(isOk){
                        System.out.println("在字符串"+str+"中大中小括号都是匹配的.");
                    }
                }catch(Exception e){
                    System.out.println("在字符串"+str+"中,"+e.getMessage());
                }
            }
        }
    }

    输出:

    在字符串5+2*(3+3)中大中小括号都是匹配的.
    在字符串{[(2+4)*8]/6}中大中小括号都是匹配的.
    在字符串[()]}中,位于第5位的字符}没有对应的匹配项
    在字符串{[(]}中,位于第4位的字符]没有对应的匹配项
    在字符串{[](中,位于第4位的字符(没有对应的匹配项,位于第1位的字符{没有对应的匹配项,
    在字符串(((((())))))中大中小括号都是匹配的.
    在字符串((([((())))))中,位于第11位的字符)没有对应的匹配项
    在字符串[[[[[]]]]]中大中小括号都是匹配的.
  • 相关阅读:
    js实现弹窗后选择信息填入text标签中以及需要注意的问题
    JDBC链接mysql之后出现read-only
    面试题之心理测试题及答案
    互联网经济思维故事
    模板
    工具包、类
    开源项目
    项目开发工具
    Java API 常用 详解
    spring文章
  • 原文地址:https://www.cnblogs.com/heyang78/p/3868388.html
Copyright © 2011-2022 走看看