[BaekJoon] 4949번 - 균형잡힌 세상 [Java][C++]
[BaekJoon] 4949번 - 균형잡힌 세상 [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
42
43
44
45
46
47
48
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));
while (true) {
String str = br.readLine();
if (str.equals(".")) break;
Deque<Character> stack = new ArrayDeque<>();
boolean isPossible = true;
for (char c : str.toCharArray()) {
if (c == '(' || c == '[') {
stack.push(c);
} else if (c == ')' || c == ']') {
if (stack.isEmpty()) {
isPossible = false;
break;
}
if (stack.peek() == '(' && c == ')' || stack.peek() == '[' && c == ']') {
stack.pop();
} else {
isPossible = false;
break;
}
}
}
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
42
43
44
45
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
while (true) {
string s;
getline(cin, s);
if (s == ".") break;
stack<char> st;
bool flag = true;
for (char c : s) {
if (c == '(' || c == '[') {
st.push(c);
} else if (c == ')' || c == ']') {
if (st.empty()) {
flag = false;
break;
}
if (st.top() == '(' && c == ')' || st.top() == '[' && c == ']') {
st.pop();
} else {
flag = false;
break;
}
}
}
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.