用栈来校验---分隔符匹配---的java算法

import java.util.Stack;

public class BracketChecker {



    public static void main(String[] args) {
        if(args.length<1) {
            System.out.println(" please enter the input string containing delimiters that needs to be checked.");
            System.exit(0);
        }
        System.out.println("the input string is: "+args[0]);
        boolean matchFlag=true;
        Stack<Character> theStack=new Stack<Character>();
        for(int j=0; j<args[0].length(); j++) {
            char ch=args[0].charAt(j);
            switch(ch) {
            case '{':
            case '[':
            case '(':
                theStack.push(ch);
                break;
            case '}':
            case ']':
            case ')':
                if(theStack.empty()) {
                    System.out.println("Error : prematurely empty! nothing matches final "+ch+" at  index "+j);
                    matchFlag=false;
                } else {
                    char chx=theStack.pop();
                    if( (ch=='}' && chx!='{')||
                            (ch==']' && chx!='[')||
                            (ch==')' && chx!='(') ) {
                        System.out.println("Error : "+ch+" doesn't match the previous "+chx+" at index "+j);
                        matchFlag=false;
                    }
                }
                break;
            default:
                break;
            } //end switch
        }//end for  loop
        //在这里,所有的字符都被处理了,如果此时栈中还有字符
        if(!theStack.empty()) {
            matchFlag=false;
            String temp="";
            while(!theStack.empty()) {
                temp+=theStack.pop();
            }
            System.out.println("Error : missing right delimiter "+temp);
        }
        if( matchFlag) {
            System.out.println("Correct! the delimiters of the original string are all matched .");
        }
    }




}



点赞