Repository navigation
Expand file tree
/
Copy pathPG_kakao_bracket.java
More file actions
85 lines (70 loc) · 1.93 KB
/
Copy pathPG_kakao_bracket.java
File metadata and controls
85 lines (70 loc) · 1.93 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package programmers.level_2;
import java.util.Stack;
class Solution {
int index = 0;
public String solution(String p) {
// 1.
if(p.isEmpty()) {
return p;
}
// 2. p to u, v
isCorrect(p);
String u = p.substring(0, index);
String v = p.substring(index);
// 3.
if(isCorrect(u)) {
return u + solution(v);
}
else { // 4.
String temp = "(" + solution(v) + ")";
u = u.substring(1, u.length() - 1);
for (int i = 0; i < u.length(); i++) {
if (String.valueOf(u.charAt(i)).equals("(")) {
temp = temp.concat(")");
} else {
temp = temp.concat("(");
}
}
return temp;
}
}
public boolean isCorrect(String p) {
Stack<Character> stack = new Stack<>();
boolean flagC = true;
int open = 0, close = 0; // number of (, )
boolean flag = true;
for (int i = 0; i < p.length(); i++) {
if(String.valueOf(p.charAt(i)).equals("(")) {
open++;
}
else {
close++;
}
if(open < close) {
flagC = false;
}
if(stack.isEmpty()) {
stack.push(p.charAt(i));
}
else {
if(stack.peek().equals(p.charAt(i))) {
stack.push(p.charAt(i));
}
else {
stack.pop();
}
}
if(flag && open == close) {
flag = false;
index = open * 2;
}
}
return flagC;
}
}
public class PG_kakao_bracket {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.solution("()))((()"));
}
}