File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .*;
2
+
3
+ class Solution {
4
+
5
+ // "균형잡힌 괄호 문자열"의 인덱스 반환
6
+ public int balancedIndex (String p ) {
7
+ int count = 0 ; // 왼쪽 괄호의 개수
8
+ for (int i = 0 ; i < p .length (); i ++) {
9
+ if (p .charAt (i ) == '(' ) count += 1 ;
10
+ else count -= 1 ;
11
+ if (count == 0 ) return i ;
12
+ }
13
+ return -1 ;
14
+ }
15
+
16
+ // "올바른 괄호 문자열"인지 판단
17
+ public boolean checkProper (String p ) {
18
+ int count = 0 ; // 왼쪽 괄호의 개수
19
+ for (int i = 0 ; i < p .length (); i ++) {
20
+ if (p .charAt (i ) == '(' ) count += 1 ;
21
+ else {
22
+ if (count == 0 ) { // 쌍이 맞지 않는 경우에 false 반환
23
+ return false ;
24
+ }
25
+ count -= 1 ;
26
+ }
27
+ }
28
+ return true ; // 쌍이 맞는 경우에 true 반환
29
+ }
30
+
31
+ public String solution (String p ) {
32
+ String answer = "" ;
33
+ if (p .equals ("" )) return answer ;
34
+ int index = balancedIndex (p );
35
+ String u = p .substring (0 , index + 1 );
36
+ String v = p .substring (index + 1 );
37
+ // "올바른 괄호 문자열"이면, v에 대해 함수를 수행한 결과를 붙여 반환
38
+ if (checkProper (u )) {
39
+ answer = u + solution (v );
40
+ }
41
+ // "올바른 괄호 문자열"이 아니라면 아래의 과정을 수행
42
+ else {
43
+ answer = "(" ;
44
+ answer += solution (v );
45
+ answer += ")" ;
46
+ u = u .substring (1 , u .length () - 1 ); // 첫 번째와 마지막 문자를 제거
47
+ String temp = "" ;
48
+ for (int i = 0 ; i < u .length (); i ++) {
49
+ if (u .charAt (i ) == '(' ) temp += ")" ;
50
+ else temp += "(" ;
51
+ }
52
+ answer += temp ;
53
+ }
54
+ return answer ;
55
+ }
56
+ }
You can’t perform that action at this time.
0 commit comments