[BaekJoon] 9012번 - 괄호 [Java][C++]
[BaekJoon] 9012번 - 괄호 [Java][C++]
1. 문제 풀이
괄호가 짝이 맞는지 판단하는 문제로 스택 자료구조를 활용해 여는 괄호는 스택에 넣고 닫는 괄호는 스택에 여는 괄호가 있는지 판단하면 된다.
2. 코드
1. 풀이 [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
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int T = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= T; tc++) {
Deque<Character> stack = new ArrayDeque<>();
boolean isPossible = true;
String str = br.readLine();
for (char c : str.toCharArray()) {
if (c == '(') {
stack.push(c);
} else {
if (stack.isEmpty()) {
isPossible = false;
break;
} else {
stack.pop();
}
}
}
if (!stack.isEmpty()) {
isPossible = false;
}
if (isPossible) {
bw.write("YES\n");
} else {
bw.write("NO\n");
}
}
bw.flush();
}
}
2. 풀이 [C++]
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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
for (int tc = 1; tc <= t; tc++) {
stack<int> st;
bool flag = true;
string s;
cin >> s;
for (char c : s) {
if (c == '(') {
st.push(c);
} else {
if (st.empty()) {
flag = false;
break;
} else {
st.pop();
}
}
}
if (!st.empty()) {
flag = false;
}
if (flag) {
cout << "YES\n";
} else {
cout << "NO\n";
}
}
}
This post is licensed under CC BY 4.0 by the author.