Maciano
Maciano

Reputation: 3

find if the brackets are properly nested/aligned JAVA

I was wondering if this approach is ok or if there is any better structure to find if the brackets are properly nested/aligned. My concern is the complexity is increase due to isMatrixZero() method.

public static boolean areBracketsCurlyParenthesisAligned(String input){
int numOpen = countOpens(input);
int[][] symbols = new int[numOpen][3];

for (int i=0; i < input.length(); i++){
    int j=0; // level 0
        switch (input.charAt(i)){
            case '[': 
                symbols[j][0]++;
                j++;
                break;
            case ']':
                j--;
                symbols[j][0]--;
                break;
            case '{':
                symbols[j][1]++;
                j++;
                break;
            case '}':
                j--;
                symbols[j][1]--;
                break;
            case '(':
                symbols[j][2]++;
                j++;
                break;
            case ')':
                j--;
                symbols[j][2]--;
                break;
            default:
                break;
            }
        if (symbols[0][0] < 0 || symbols[0][1] < 0 || symbols[0][2] < 0) return false;
    } 
    // All symbol variables value should be 0 at the end
    if (isMatrixZero(symbols)) return true;
    else return false;
}
private static int countOpens(String str){
    int opens=0;
    for (int i=0; i< str.length(); i++){
        if (str.charAt(i) == '[' || str.charAt(i) == '{' || str.charAt(i) == '(') opens++;
    }
    return opens;
}

private static boolean isMatrixZero(int[][] matrix){
    for (int i=0; i < matrix.length;i++){
        for (int j=0; j < matrix[0].length;j++){
            if (matrix[i][j] != 0) return false;
        }
    }
    return true;
}

}

Any suggestion is welcomed!

Upvotes: 0

Views: 802

Answers (1)

MuchHelping
MuchHelping

Reputation: 631

Why not use stacks? Instead of strings you can use HashMap, opening brackets would be keys, closing would be value.

private final static String openingBrackets = "([{<";
private final static String closingBrackets = ")]}>";

public static boolean checkBrackets(String input) {
    Stack<Character> openedBrackets = new Stack<Character>();
    HashMap brackets = new HashMap();

    char[] inputs = input.toCharArray();
    int x = 0;
    for (char c : inputs) {
        if (openingBrackets.indexOf(c) != -1) {
            openedBrackets.push(c);
        } else if (closingBrackets.indexOf(c) != -1) {
            if (openedBrackets.isEmpty())
                return false;
            if (Math.abs(openedBrackets.pop() - c) > 2)
                return false;
        }

        x++;
        if (openedBrackets.size() > inputs.length - x)
            return false;
    }

    return openedBrackets.isEmpty();
}

Also, here is the same question Checking string has balanced parentheses

Upvotes: 1

Related Questions