728x90

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

 

9012번: 괄호

괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고

www.acmicpc.net

 

 

 

풀이)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;

public class Main_BJ_9012_괄호 {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        for(int k=0; k<n; k++) {
            Stack<Integer> stack = new Stack<>();
            int index = 0;
            boolean flag = false;
            String str = br.readLine();
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c == '(')
                    stack.push(index);

                else {
                    if (stack.isEmpty()) {
                        System.out.println("NO");
                        flag = true;
                        break;
                    } else
                        stack.pop();
                }
            }//for
            if(!flag){
                if(stack.isEmpty())
                    System.out.println("YES");
                else
                    System.out.println("NO");
            }
        }

    }
}

스택을 이용하면 간단한 문제다.

'('가 나올 때마다 stack에 push 해주고, ')'가 나올때마다 pop을 해주면 된다.

이때, stack에서 pop할때 스택 언더플로우가 발생할 수 있고, 발생할 경우 출력해주면 끝난다.

 

따라서 flag 변수를 따로 만들어줘서 중간에 나온 애인지 체크해준후,

스택에 push, pop 과정이 모두 종료되면 stack이 비어있는지 확인하고 출력해주면 된다.

 

간단한 문제!

728x90

'코테 > 백준' 카테고리의 다른 글

백준 10845 큐(JAVA)  (0) 2023.03.16
백준 10814 나이순 정렬(JAVA)  (0) 2023.03.14
백준 2775 부녀회장이 될테야(JAVA)  (0) 2023.03.12
백준 9465 스티커(JAVA)  (0) 2023.03.11
백준 2751 수 정렬하기2(JAVA)  (0) 2023.03.11

+ Recent posts