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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
import org.junit.Test;
import java.util.*;
import java.util.stream.*;
public class SolutionTest {
@Test
public void fixedTests() {
for (String[] trial : new String[][]{
{"example(unwanted thing)example", "exampleexample"},
{"example(unwanted thing)example", "exampleexample"},
{"example (unwanted thing) example", "example example"},
{"a (bc d)e", "a e"},
{"a(b(c))", "a"},
{"hello example (words(more words) here) something", "hello example something"},
{"(first group) (second group) (third group)", " "}})
Tester.doTest(trial[0], trial[1]);
}
private static final String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
private static final Random rand = new Random();
private static String randomLetter() {
int i = rand.nextInt(letters.length());
return letters.substring(i, i+1);
}
@Test
public void randomTests() {
for (int trial = 1; trial <= 100; trial++) {
String str = IntStream.range(0, rand.nextInt(200)+2)
.mapToObj(i -> randomLetter())
.collect(Collectors.joining(""));
for (int parens = rand.nextInt(str.length()/2); 0 < parens--;) {
int open = rand.nextInt(str.length()-1), close = rand.nextInt(str.length()-open) + open;
str = str.substring(0, open) + "(" + str.substring(open, close) + ")" + str.substring(close);
}
Tester.doTest(str, solution(str));
}
}
private String solution(final String str) {
StringBuilder sb = new StringBuilder();
int depth = 0;
for (char c : str.toCharArray()) {
depth += '(' == c ? 1 : 0;
if ( 0 == depth ) sb.append(c);
depth -= ')' == c ? 1 : 0;
}
return sb.toString();
}
}
|