๐งฉ Baekjoon 9012 - ๊ดํธ
๋ฌธ์
๊ดํธ ๋ฌธ์์ด(Parenthesis String, PS)์ ๋ ๊ฐ์ ๊ดํธ ๊ธฐํธ์ธ โ(โ ์ โ)โ ๋ง์ผ๋ก ๊ตฌ์ฑ๋์ด ์๋ ๋ฌธ์์ด์ด๋ค. ๊ทธ ์ค์์ ๊ดํธ์ ๋ชจ์์ด ๋ฐ๋ฅด๊ฒ ๊ตฌ์ฑ๋ ๋ฌธ์์ด์ ์ฌ๋ฐ๋ฅธ ๊ดํธ ๋ฌธ์์ด(Valid PS, VPS)์ด๋ผ๊ณ ๋ถ๋ฅธ๋ค. ํ ์์ ๊ดํธ ๊ธฐํธ๋ก ๋ โ( )โ ๋ฌธ์์ด์ ๊ธฐ๋ณธ VPS ์ด๋ผ๊ณ ๋ถ๋ฅธ๋ค. ๋ง์ผ x ๊ฐ VPS ๋ผ๋ฉด ์ด๊ฒ์ ํ๋์ ๊ดํธ์ ๋ฃ์ ์๋ก์ด ๋ฌธ์์ด โ(x)โ๋ VPS ๊ฐ ๋๋ค. ๊ทธ๋ฆฌ๊ณ ๋ VPS x ์ y๋ฅผ ์ ํฉ(concatenation)์ํจ ์๋ก์ด ๋ฌธ์์ด xy๋ VPS ๊ฐ ๋๋ค. ์๋ฅผ ๋ค์ด โ(())()โ์ โ((()))โ ๋ VPS ์ด์ง๋ง โ(()(โ, โ(())()))โ , ๊ทธ๋ฆฌ๊ณ โ(()โ ๋ ๋ชจ๋ VPS ๊ฐ ์๋ ๋ฌธ์์ด์ด๋ค.ย
์ฌ๋ฌ๋ถ์ ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง ๊ดํธ ๋ฌธ์์ด์ด VPS ์ธ์ง ์๋์ง๋ฅผ ํ๋จํด์ ๊ทธ ๊ฒฐ๊ณผ๋ฅผ YES ์ NO ๋ก ๋ํ๋ด์ด์ผ ํ๋ค.
์ ๋ ฅ
์ ๋ ฅ ๋ฐ์ดํฐ๋ ํ์ค ์ ๋ ฅ์ ์ฌ์ฉํ๋ค. ์ ๋ ฅ์ T๊ฐ์ ํ ์คํธ ๋ฐ์ดํฐ๋ก ์ฃผ์ด์ง๋ค. ์ ๋ ฅ์ ์ฒซ ๋ฒ์งธ ์ค์๋ ์ ๋ ฅ ๋ฐ์ดํฐ์ ์๋ฅผ ๋ํ๋ด๋ ์ ์ T๊ฐ ์ฃผ์ด์ง๋ค. ๊ฐ ํ ์คํธ ๋ฐ์ดํฐ์ ์ฒซ์งธ ์ค์๋ ๊ดํธ ๋ฌธ์์ด์ด ํ ์ค์ ์ฃผ์ด์ง๋ค. ํ๋์ ๊ดํธ ๋ฌธ์์ด์ ๊ธธ์ด๋ 2 ์ด์ 50 ์ดํ์ด๋ค.
์ถ๋ ฅ
์ถ๋ ฅ์ ํ์ค ์ถ๋ ฅ์ ์ฌ์ฉํ๋ค. ๋ง์ผ ์ ๋ ฅ ๊ดํธ ๋ฌธ์์ด์ด ์ฌ๋ฐ๋ฅธ ๊ดํธ ๋ฌธ์์ด(VPS)์ด๋ฉด โYESโ, ์๋๋ฉด โNOโ๋ฅผ ํ ์ค์ ํ๋์ฉ ์ฐจ๋ก๋๋ก ์ถ๋ ฅํด์ผ ํ๋ค.
์์
โ ์ ๋ ฅ 1
1
2
3
4
5
6
7
6
(())())
(((()())()
(()())((()))
((()()(()))(((())))()
()()()()(()()())()
(()((())()(
โ ์ถ๋ ฅ 1
1
2
3
4
5
6
NO
NO
YES
NO
YES
NO
โ ์ ๋ ฅ 2
1
2
3
4
3
((
))
())(()
โ ์ถ๋ ฅ 2
1
2
3
NO
NO
NO
์์ฑ ์ฝ๋
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
// 1. ๋ณ์ ์ ์ธ ๋ฐ ์ด๊ธฐํ
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
// 2. ํ
์คํธ ์ผ์ด์ค ๋ฐ๋ณต
for (int i = 0; i < n; i++) {
// ๋ณ์ ์ ์ธ ๋ฐ ์ด๊ธฐํ
List<Character> list = new ArrayList<>();
char[] chars = br.readLine().toCharArray();
// ์
๋ ฅ ๊ฐ ์ํ
for (char c : chars) {
int lastIdx = list.size() - 1;
if (!list.isEmpty() && list.get(lastIdx) == '(' && c == ')') {
list.remove(lastIdx);
} else {
list.add(c);
}
}
// VPS ์ฌ๋ถ ๋ฌธ์์ด ์กฐํฉ
sb.append((!list.isEmpty()) ? "NO" : "YES");
// ์ถ๋ ฅ
System.out.println(sb);
sb.setLength(0);
}
}
}