I want to test if an input String is balanced. It would be balanced if there is a matching opening and closing parenthesis, bracket or brace.
example:
{} bal
I wrote this code to solve this problem using only an integer (or maybe a byte) variable per bracket type.
public boolean checkWithIntegers(String input) {
int brackets = 0;
for (char c: input.toCharArray()) {
switch (c) {
case '(':
brackets++;
break;
case ')':
if (brackets == 0)
return false;
brackets--;
break;
default:
break;
}
}
return brackets == 0;
}
public static void main(String... args) {
Borrar b = new Borrar();
System.out.println( b.checkWithIntegers("") );
System.out.println( b.checkWithIntegers("(") );
System.out.println( b.checkWithIntegers(")") );
System.out.println( b.checkWithIntegers(")(") );
System.out.println( b.checkWithIntegers("()") );
}
OBS
Hope this help. Cheers!