爪哇国新游记之十九----使用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位的字符)没有对应的匹配项
在字符串[[[[[]]]]]中大中小括号都是匹配的.
posted @   逆火狂飙  阅读(201)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东
点击右上角即可分享
微信分享提示