forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBracketSequences.java
More file actions
30 lines (27 loc) · 896 Bytes
/
BracketSequences.java
File metadata and controls
30 lines (27 loc) · 896 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package combinatorics;
import java.util.Arrays;
public class BracketSequences {
public static boolean nextBracketSequence(char[] s) {
int n = s.length;
for (int i = n - 1, balance = 0; i >= 0; i--) {
balance += s[i] == '(' ? -1 : 1;
if (s[i] == '(' && balance > 0) {
--balance;
int open = (n - i - 1 - balance) / 2;
int close = n - i - 1 - open;
s[i] = ')';
Arrays.fill(s, i + 1, i + 1 + open, '(');
Arrays.fill(s, i + 1 + open, i + open + close, ')');
return true;
}
}
return false;
}
// Usage example
public static void main(String[] args) {
char[] s = "((()))".toCharArray();
do {
System.out.println(new String(s));
} while (nextBracketSequence(s));
}
}