栈实现分隔符匹配

public class StackX {
    private int maxSize;
    private char[] stackArray;
    private int top;
    
    //栈构造方法
    public StackX(int max){
        stackArray = new char[max];
        top = -1;
        maxSize = max;
    }
    
    //入栈
    public void push(char ch){
        stackArray[++top] = ch;//top先自增1在执行表达式
    }
    
    //出栈
    public char pop(){
        return stackArray[top--];//执行表达式后top自减1
    }
    
    //查看栈顶
    public int peek(){
        return stackArray[top];
    }
    
    //判断是为空
    public boolean isEmpty(){
        return top==-1;
    }
    
    //判断栈是否满
    public boolean isFull(){
        return top==(maxSize-1);
    }
}

class BracketChecker{
    private String input;
    public BracketChecker(String str){
        input = str;
    }
    public void check(){
        int maxSize = input.length();
        StackX theStack = new StackX(maxSize);
        for(int i=0; i<maxSize; i++){
            char ch = input.charAt(i);
            
            switch(ch){
            case '{':
            case '[':
            case '(':
                theStack.push(ch);
                break;//结束循环
            case '}':
            case ']':
            case ')':
                if(!theStack.isEmpty()){// if stack not empty
                    char chx = theStack.pop();
                    if((ch == '}' && chx != '{')
                        ||(ch == ']' && chx != '[')
                        ||(ch == ')' && chx != '(')){
                        System.out.println("Error: "+ch+" at "+i);
                    }
                }
                else
                    System.out.println("Error: "+ch+" at "+i);
                
                break;
            default:
                break;
            }//end switch
        }//end for
    }//end check
}
public class BracketApp {
    public static void main(String[] args) throws IOException{
        String input ;
        int i=0;
        while(true){
            System.out.println("enter String");
            input = getString();
            if(" ".equals(input))
                break;
            BracketChecker check = new BracketChecker(input);
            check.check();
            i++;
            System.out.println(i);
        }//end while
    }//end main
    
    public static String getString() throws IOException{
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader bs = new BufferedReader(isr);
        String str = bs.readLine();
        return str;
    }
}

 

posted @ 2013-01-26 10:02  tangrongyue  Views(322)  Comments(0Edit  收藏  举报