38 lines
952 B
Plaintext
38 lines
952 B
Plaintext
module BalancedBrackets {
|
|
Boolean balanced(String text) {
|
|
Int depth = 0;
|
|
for (Char ch : text) {
|
|
switch (ch, depth) {
|
|
case ('[', _):
|
|
++depth;
|
|
break;
|
|
case (']', 0):
|
|
return False;
|
|
case (']', _):
|
|
--depth;
|
|
break;
|
|
}
|
|
}
|
|
return depth==0;
|
|
}
|
|
|
|
@Inject Console console;
|
|
void run() {
|
|
String[] tests =
|
|
[
|
|
"[]",
|
|
"[][]",
|
|
"[]][[]",
|
|
"[[[]][]]",
|
|
"][[[[]][]]",
|
|
"[[[]][[]][]]",
|
|
"]][[]][[[[][]]",
|
|
"[[]]]][]][[][[[]",
|
|
];
|
|
Int longest = tests.map(s -> s.size).reduce(0, (max, len) -> max.maxOf(len));
|
|
for (String test : tests) {
|
|
console.print($"{test}{' ' * (longest-test.size)} {balanced(test) ? "OK" : "NOT OK"}");
|
|
}
|
|
}
|
|
}
|