检查给定的String是否具有相同的匹配括号

Zai*_*nau 0 java

在网上发现了一些有趣的解决问题的问题.

You are to check the given String str if they contains matching parenthesis.
Run Code Online (Sandbox Code Playgroud)

示例输入: [],[(]),{[]},{[}],{[}),{]}

输出示例: EQUAL,EQUAL,EQUAL,EQUAL,NOT EQUAL,NOT EQUAL

我已经设法使用基础知识完成了对此功能的要求,只是想知道是否有更好的方法吗?

String str = "{[(])}(){}";
    int pairs = 0;
    boolean unableToFind = false;
    ArrayList<Character> anChar = new ArrayList<Character>();

    for (int i = 0; i < str.length(); i++) {
        anChar.add(str.charAt(i));
    }

    if (str.length() % 2 == 0) { 
        while (pairs != str.length() / 2) {
            for (int i = 1; i < anChar.size(); i++) {
                char a = (char) anChar.get(0);
                char b = (char) anChar.get(i);
                if (a == '{' && b == '}' || a == '[' && b == ']' || a == '(' && b == ')') {
                    anChar.remove(i);
                    anChar.remove(0);
                    pairs++;
                    break;
                } else {
                    if (i == anChar.size() - 1) { // reached end of array
                        unableToFind = true;
                        break;
                    }
                }
            }
            if (unableToFind)
                break;
        }

        if (pairs == str.length() / 2) {
            System.out.println("Log#01: The String have balanced parenthesis");
        } else {
            System.out.println("Log#02: The String do not have balanced parenthesis. (" + pairs + "/" + str.length() / 2 + " pairs found)");
        }
    } else {
        System.out.println("Log#03: The String do not have even numbers of parenthesis");
    }
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

你的方法过于复杂.所有你需要的是三个计数器- countRound,countSquarecountCurly.将所有三个初始化为零,然后逐个字符地遍历字符串.如果你看到一个开括号,增加它的计数器; 如果它是一个右括号,则递减其相应的计数器.一旦循环结束,所有三个计数器必须为零; 否则括号的数量不匹配.

注意:这并没有检查括号是平衡的,因为你的例子并不需要它(即"[(])"生产"EQUAL"甚至通过输入不平衡).