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!