# ★★☆☆☆ 괄호변환
# 구현코드
import java.util.Stack;
public class Solution {
public String solution(String p) {
return solve(p);
}
public String solve(String input){
if(input.length() == 0)
return "";
int checkPoint = 0;
int find = 0;
Stack<Character> stack = new Stack<>();
do{
stack.add(input.charAt(checkPoint));
if(input.charAt(checkPoint++) == '(')
find++;
else
find--;
}while (find != 0);
int closeCount = 0;
boolean isRight = true;
while (!stack.isEmpty()){
char p = stack.pop();
if(p == ')')
closeCount ++;
else
closeCount --;
if(closeCount < 0){
isRight = false;
break;
}
}
if(isRight) {
return input.substring(0, checkPoint) + solve(input.substring(checkPoint));
}
String result = "(" + solve(input.substring(checkPoint)) + ")";
String u = input.substring(1,checkPoint-1);
String reverseU = "";
for(int i = 0; i < u.length(); i ++){
if(u.charAt(i) == '(')
reverseU = reverseU + ")";
else
reverseU = reverseU + "(";
}
return result + reverseU;
}
}
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
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