括号匹配

package 括号匹配;


import java.util.Stack;

public class 括号匹配 {
    public static void main(String[] args) {
        
        Stack<Character> stack = new Stack<Character>();
        char[] ch = { ')', ')', '[', ']' };
        boolean flag = true;
        for (int i = 0; i < ch.length; i++) {
            if ((i == 0) && (ch[i] == ')' || ch[i] == ']')) {
                System.out.println("no0");
                flag = false;
                break;
            }

            switch (ch[i]) {
            case '(':
                stack.push(ch[i]);
                break;
            case ')':
                if (stack.isEmpty()) {
                    System.out.println("no1");
                    flag = false;
                    break;
                } else {
                    if (!stack.pop().equals('(')) {
                        System.out.println("no2");
                        flag = false;
                        break;
                    }
                }

                break;
            case '[':
                stack.push(ch[i]);
                break;
            case ']':
                if (stack.isEmpty()) {
                    System.out.println("no3");
                    flag = false;
                    break;
                } else {
                    if (!stack.pop().equals('[')) {
                        System.out.println("no4");
                        flag = false;
                        break;
                    }
                }
                break;
            }

        }

        if (flag) {
            System.out.println("ok");
        }
    }
}

 

posted @ 2015-09-24 21:47  大数据从业者FelixZh  阅读(239)  评论(0编辑  收藏  举报