forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path4.java
56 lines (52 loc) Β· 1.86 KB
/
4.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
import java.util.*;
class Solution {
// "κ· νμ‘ν κ΄νΈ λ¬Έμμ΄"μ μΈλ±μ€ λ°ν
public int balancedIndex(String p) {
int count = 0; // μΌμͺ½ κ΄νΈμ κ°μ
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') count += 1;
else count -= 1;
if (count == 0) return i;
}
return -1;
}
// "μ¬λ°λ₯Έ κ΄νΈ λ¬Έμμ΄"μΈμ§ νλ¨
public boolean checkProper(String p) {
int count = 0; // μΌμͺ½ κ΄νΈμ κ°μ
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') count += 1;
else {
if (count == 0) { // μμ΄ λ§μ§ μλ κ²½μ°μ false λ°ν
return false;
}
count -= 1;
}
}
return true; // μμ΄ λ§λ κ²½μ°μ true λ°ν
}
public String solution(String p) {
String answer = "";
if (p.equals("")) return answer;
int index = balancedIndex(p);
String u = p.substring(0, index + 1);
String v = p.substring(index + 1);
// "μ¬λ°λ₯Έ κ΄νΈ λ¬Έμμ΄"μ΄λ©΄, vμ λν΄ ν¨μλ₯Ό μνν κ²°κ³Όλ₯Ό λΆμ¬ λ°ν
if (checkProper(u)) {
answer = u + solution(v);
}
// "μ¬λ°λ₯Έ κ΄νΈ λ¬Έμμ΄"μ΄ μλλΌλ©΄ μλμ κ³Όμ μ μν
else {
answer = "(";
answer += solution(v);
answer += ")";
u = u.substring(1, u.length() - 1); // 첫 λ²μ§Έμ λ§μ§λ§ λ¬Έμλ₯Ό μ κ±°
String temp = "";
for (int i = 0; i < u.length(); i++) {
if (u.charAt(i) == '(') temp += ")";
else temp += "(";
}
answer += temp;
}
return answer;
}
}