public class BraceCheck {
public static void main(String[] args) {
String[] tapes = {
"01,{01,0,{10,1,{0,1},{1}}},1",
"1,0,0{0}},{{{1,0}},1,0}",
"0,1,{{0,0},{1},{{{0}},1"
};
for(int j = 0; j < tapes.length; j++) {
System.out.printf("checkBraces(tapes[%d]): = %s%n",
j, checkBraces(tapes[j]));
}
}
private static String checkBraces(String tape) {
int len = tape.length();
//System.out.println("len = " + len);
int headPos = 0;
// Find first left brace.
while(tape.charAt(headPos) != '{' && headPos < len)
headPos++;
int leftBraceIndex = headPos;
//System.out.printf("leftBraceIndex = %d%n", leftBraceIndex);
// Find index of a matching right brace.
int match = 0;
do {
headPos++;
if(tape.charAt(headPos) == '{')
match--;
if(tape.charAt(headPos) == '}')
match++;
} while(headPos < len-1);
String result = "ILLEGAL STATE";
if(match < 1)
result = "TOO MANY '{'";
if(match == 1)
result = "VALID DATA";
if(match > 1)
result = "TOO MANY '}'";
return result;
}
}