forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path4.java
More file actions
56 lines (52 loc) ยท 1.86 KB
/
4.java
File metadata and controls
56 lines (52 loc) ยท 1.86 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
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;
}
}