-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertBracket.java
67 lines (62 loc) · 2.05 KB
/
InsertBracket.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.Scanner;
/**
* Compound
* C(o(m(po)u)n)d
* Compounds
* C(o(m(p(o)u)n)d)s
* CompoundUndoManager
* C(o(m(p(o(u(n(d(U(n)d)o)M)a)n)a)g)e)r
* CompoundUndoManagers
* C(o(m(p(o(u(n(d(U(nd)o)M)a)n)a)g)e)r)s
* CompoundUndoManagers
* C(o(m(p(o(u(n(d(U(nd)o)M)a)n)a)g)e)r)s
*/
public class InsertBracket {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println(brackets(input, 1, input.length()));
System.out.println(brackets(input));
brackets(input, 0);
scanner.close();
}
private static void brackets(String input, int index) {
if (index >= input.length()) {
return;
}
if (input.length() % 2 == 0 && (input.length() / 2) - 1 == index) {
System.out.print(input.charAt(index));
System.out.print(input.charAt(index + 1));
index = index + 2;
} else if (input.length() % 2 > 0 && input.length() / 2 == index) {
System.out.print(input.charAt(index));
index = index + 1;
}
if (input.length() / 2 > index) {
System.out.print(input.charAt(index));
System.out.print("(");
} else if (input.length() / 2 < index) {
System.out.print(")");
System.out.print(input.charAt(index));
}
index = index + 1;
brackets(input, index);
}
private static String brackets(String input, int i, int j) {
input = input.substring(0, i) + "(" + input.substring(i, j - 1) + ")" +
input.substring(j - 1);
i = i + 2;
if (j - i == 1 || i == j) {
return input;
}
return brackets(input, i, j);
}
private static String brackets(String input) {
if (input.length() <= 2) {
return input;
}
return input.substring(0, 1) + "(" +
brackets(input.substring(1, input.length() - 1)) +
")" + input.substring(input.length() - 1);
}
}