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
Following is a Java
code sample to detect if a string is balanced.
http://introcs.cs.princeton.edu/java/43stack/Parentheses.java.html
The idea is that -
( [ {
, push it on the stack. ) ] }
, try to pop a matching opening brace ( [ }
from stack. If you can't find a matching opening brace, then string is not balanced. 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!