백준 4949번(스택 구조)

김경욱·2025년 9월 11일

백준

목록 보기
73/121

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.*;

import static java.util.Collections.*;

public class Main {
public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    while(true)
    {
        String line = br.readLine();

        if (line.equals("."))
        {

            break;
        }

        Stack<Character> stack = new Stack<>();

       boolean balanced = true;

       for (char ch : line.toCharArray() )
       {
           if (ch =='(' || ch == '[')
           {
               stack.push(ch);
           }
            if (ch ==')' )
           {
               if (stack.isEmpty() == true || stack.peek() != '(')
               {
                 balanced = false;

                 break;
               }
               stack.pop();

           }


            if (ch == ']')
            {
                if (stack.isEmpty() || stack.peek() != '[')
                {
                    balanced= false;
                  break;

                }

                stack.pop();


            }




       }

        if (balanced ==true && stack.isEmpty())
        {
            System.out.println("yes");
        }

        else  
        {
            System.out.println("no");
        }

    }





}

}

처음 배우는 스택구조여서 어려웠다. 조건들도 많고 boolean을 이용하고 Stack이 비어있는지까지 확인해야 해서 어려웠던 것 같다.

0개의 댓글