The Java program below gives one possible answer in bold red.
class Parens {
int level = 0;
GetChar getChar = new GetChar();
char next;
String pOut = "";
void P() {
scan();
Q();
if (next == '#') System.out.println(pOut);
else error(1);
}
void Q() {
if (next == '(') {
scan();
pOut += "(" + level++ + " ";
}
else error(2);
R();
}
void R() {
if (next == ')') {
scan();
pOut += " " + --level + ")";
}
else {
Q();
R();
}
}
void scan() {
while (Character.isWhitespace(next = getChar.getNextChar()))
;
}
void error(int n) {
System.out.println("*** ERROR: " + n);
System.exit(1);
}
public static void main(String[] args) {
Parens parens = new Parens();
parens.P();
}
}
Here are three separate runs (boldface = input):
(()())# (0 (1 1)(1 1) 0) ( () (( )) (() () ) () ) # (0 (1 1)(1 (2 2) 1)(1 (2 2)(2 2) 1)(1 1) 0) ((((((((((()))))))))))# (0 (1 (2 (3 (4 (5 (6 (7 (8 (9 (10 10) 9) 8) 7) 6) 5) 4) 3) 2) 1) 0) ( () (( )) (()) () (((() (()) ) () ) ) )# (0 (1 1)(1 (2 2) 1)(1 (2 2) 1)(1 1)(1 (2 (3 (4 4)(4 (5 5) 4) 3)(3 3) 2) 1) 0)