|
| 1 | +importjava.util.*; |
| 2 | + |
| 3 | +classSolution { |
| 4 | + |
| 5 | +// "균형잡힌 괄호 문자열"의 인덱스 반환 |
| 6 | +publicintbalancedIndex(Stringp) { |
| 7 | +intcount =0;// 왼쪽 괄호의 개수 |
| 8 | +for (inti =0;i <p.length();i++) { |
| 9 | +if (p.charAt(i) =='(')count +=1; |
| 10 | +elsecount -=1; |
| 11 | +if (count ==0)returni; |
| 12 | + } |
| 13 | +return -1; |
| 14 | + } |
| 15 | + |
| 16 | +// "올바른 괄호 문자열"인지 판단 |
| 17 | +publicbooleancheckProper(Stringp) { |
| 18 | +intcount =0;// 왼쪽 괄호의 개수 |
| 19 | +for (inti =0;i <p.length();i++) { |
| 20 | +if (p.charAt(i) =='(')count +=1; |
| 21 | +else { |
| 22 | +if (count ==0) {// 쌍이 맞지 않는 경우에 false 반환 |
| 23 | +returnfalse; |
| 24 | + } |
| 25 | +count -=1; |
| 26 | + } |
| 27 | + } |
| 28 | +returntrue;// 쌍이 맞는 경우에 true 반환 |
| 29 | + } |
| 30 | + |
| 31 | +publicStringsolution(Stringp) { |
| 32 | +Stringanswer =""; |
| 33 | +if (p.equals(""))returnanswer; |
| 34 | +intindex =balancedIndex(p); |
| 35 | +Stringu =p.substring(0,index +1); |
| 36 | +Stringv =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 | +Stringtemp =""; |
| 48 | +for (inti =0;i <u.length();i++) { |
| 49 | +if (u.charAt(i) =='(')temp +=")"; |
| 50 | +elsetemp +="("; |
| 51 | + } |
| 52 | +answer +=temp; |
| 53 | + } |
| 54 | +returnanswer; |
| 55 | + } |
| 56 | +} |