Skip to content

Commit 4c8d85e

Browse files
committed
[Silver IV] Title: 균형잡힌 세상, Time: 572 ms, Memory: 33384 KB -BaekjoonHub
1 parent d3a6034 commit 4c8d85e

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# [Silver IV] 균형잡힌 세상 - 4949
2+
3+
[문제 링크](https://www.acmicpc.net/problem/4949)
4+
5+
### 성능 요약
6+
7+
메모리: 33384 KB, 시간: 572 ms
8+
9+
### 분류
10+
11+
자료 구조, 스택, 문자열
12+
13+
### 제출 일자
14+
15+
2024년 3월 24일 20:09:49
16+
17+
### 문제 설명
18+
19+
<p>세계는 균형이 잘 잡혀있어야 한다. 양과 음, 빛과 어둠 그리고 왼쪽 괄호와 오른쪽 괄호처럼 말이다.</p>
20+
21+
<p>정민이의 임무는 어떤 문자열이 주어졌을 때, 괄호들의 균형이 잘 맞춰져 있는지 판단하는 프로그램을 짜는 것이다.</p>
22+
23+
<p>문자열에 포함되는 괄호는 소괄호("()") 와 대괄호("[]")로 2종류이고, 문자열이 균형을 이루는 조건은 아래와 같다.</p>
24+
25+
<ul>
26+
<li>모든 왼쪽 소괄호("(")는 오른쪽 소괄호(")")와만 짝을 이뤄야 한다.</li>
27+
<li>모든 왼쪽 대괄호("[")는 오른쪽 대괄호("]")와만 짝을 이뤄야 한다.</li>
28+
<li>모든 오른쪽 괄호들은 자신과 짝을 이룰 수 있는 왼쪽 괄호가 존재한다.</li>
29+
<li>모든 괄호들의 짝은 1:1 매칭만 가능하다. 즉, 괄호 하나가 둘 이상의 괄호와 짝지어지지 않는다.</li>
30+
<li>짝을 이루는 두 괄호가 있을 때, 그 사이에 있는 문자열도 균형이 잡혀야 한다.</li>
31+
</ul>
32+
33+
<p>정민이를 도와 문자열이 주어졌을 때 균형잡힌 문자열인지 아닌지를 판단해보자.</p>
34+
35+
### 입력
36+
37+
<p>각 문자열은 마지막 글자를 제외하고 영문 알파벳, 공백, 소괄호("( )"), 대괄호("[ ]")로 이루어져 있으며, 온점(".")으로 끝나고, 길이는 100글자보다 작거나 같다.</p>
38+
39+
<div>입력의 종료조건으로 맨 마지막에 온점 하나(".")가 들어온다.</div>
40+
41+
### 출력
42+
43+
<p>각 줄마다 해당 문자열이 균형을 이루고 있으면 "yes"를, 아니면 "no"를 출력한다.</p>
44+
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import java.io.BufferedReader;
2+
import java.io.InputStreamReader;
3+
import java.io.IOException;
4+
import java.util.*;
5+
public class Main {
6+
public static void main(String[] args) throws IOException {
7+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8+
br.lines().takeWhile(l -> !l.isEmpty())
9+
.filter(s -> !s.equals("."))
10+
.map(s -> s.replaceAll("[a-zA-Z\\s.]",""))
11+
.map(s -> {
12+
Stack<Character> stack = new Stack<>();
13+
for(char c : s.toCharArray()) {
14+
if(c == '(' || c == '[') {
15+
stack.push(c);
16+
} else if(c == ')' && (stack.isEmpty() || stack.pop() != '(')) {
17+
return "no";
18+
} else if(c == ']' && (stack.isEmpty() || stack.pop() != '[')) {
19+
return "no";
20+
}
21+
}
22+
return stack.isEmpty() ? "yes" : "no";
23+
}).forEach(System.out::println);
24+
}
25+
}

0 commit comments

Comments
 (0)