BOJ

백준 9012 - 괄호

yanJuicy 2022. 1. 24. 07:02
반응형

문제

https://www.acmicpc.net/problem/9012

 

9012번: 괄호

문제 괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고 부른다. 한 쌍의 괄호 기호로 된 “( )” 문자열은 기본 VPS 이라고 부른다. 만일 x 가 VPS 라면 이것을 하나의 괄호에 넣은 새로운 문자열 “(x)”도 VPS 가 된다. 그리고 두 VPS x 와 y를 접합(conc

www.acmicpc.net

 

풀이

스택을 이용하는 간단한 문제이다. '('일 때 스택에 push 하고 ')'일 때 스택에서 pop 한다. 스택에서 pop을 할 수 없는 경우 주어진 괄호 문자열은 잘못 된 것이다. 그리고 모든 입력이 끝난 후 스택이 비어 있으면 올 바른 괄호 문자열이고, 비어 있지 않다면 잘못 된 괄호 문자열이다.

 

코드

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
#include <iostream>
#include <stack>
#include <string>
 
using namespace std;
 
int T;
string VPS;
bool fail;
 
int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
 
    cin >> T;
 
    while (T--)
    {
        cin >> VPS;
        stack<char> s;
        fail = false;
 
        for (int i = 0; i < VPS.size(); i++)
        {
            if (VPS[i] == '(') s.push(VPS[i]);
            else
            {
                if (s.empty()) fail = true;
                else s.pop();
            }
        }
        if (s.empty() && !fail) cout << "YES" << '\n';
        else cout << "NO" << '\n';
    }
 
    return 0;
}
cs

 

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
import java.util.Scanner;
 
public class Main {
 
    static int T;
    static StringBuilder sb = new StringBuilder();
    static String[] inputs;
 
    public static void main(String[] args) {
        input();
        for (int i=0; i<T; i++) {
            solve(inputs[i]);
        }
        System.out.println(sb.toString());
    }
 
    private static void solve(String str) {
        int l = 0;
 
        for (char c : str.toCharArray()) {
            if (c == '(') l++;
            else l--;
 
            if (l < 0) {
                sb.append("NO\n");
                return;
            }
        }
 
        if (l == 0)
            sb.append("YES\n");
        else
            sb.append("NO\n");
    }
 
    private static void input() {
        Scanner sc = new Scanner(System.in);
        T = sc.nextInt();
        inputs = new String[T];
        for (int i=0; i<T; i++) {
            inputs[i] = sc.next();
        }
    }
}
cs
반응형

'BOJ' 카테고리의 다른 글

백준 11286 - 절댓값 힙  (0) 2022.01.28
백준 2164 - 카드2  (0) 2022.01.25
백준 11779 - 최소비용 구하기 2  (0) 2021.08.12
백준 1916 - 최소비용 구하기  (0) 2021.08.11
백준 18352 - 특정 거리의 도시 찾기  (0) 2021.07.19