9.6 print out all valid combinations of n-pairs of parentheses

来源:互联网 发布:数控车床梯形螺纹编程 编辑:程序博客网 时间:2024/04/28 21:07

leetcode 题目变种


package test;



import java.util.Stack;


public class isValidParenthesis {


    private static boolean compareChar(char c1, char c2) {
        switch (c1) {
        case '(':
            if (c2 != ')') {
                return false;
            } else
                break;
        case '[':
            if (c2 != ']') {
                return false;
            } else
                break;
        case '{':
            if (c2 != '}') {
                return false;
            } else
                break;
        }
        return true;
    }


    private static boolean isValid(String s) {
        int c = s.length();
        Stack<Character> openS = new Stack<Character>();
        if (c <= 1)
            return false;


        for (int i = 0; i < c; i++) {
            char tmp = ' ';


            // Character ch = s.charAt(i);
            if ((s.charAt(i) == '(') || (s.charAt(i) == '[')
                    || (s.charAt(i) == '{')) {
                openS.push(s.charAt(i));
            } else {
                tmp = openS.peek();
                if(openS.isEmpty() || !compareChar(openS.pop(), s.charAt(i)))  
                    return false;
                  
                System.out.println(tmp+""+ s.charAt(i));
            }


        }


        return openS.isEmpty();


    }


    public static void main(String[] args) {
        String s = "({{{}}])";
        // System.out.println(compareChar('(', ')'));
        if (isValid(s))
            System.out.printf(" isValid");
        else
            System.out.printf(" is not  Valid");


    }

}



结果: {}
{}
 is not  Valid

0 0