백준 괄호를 이용한 스택 문제

정호윤·2023년 3월 14일

자바

목록 보기
31/46

그냥 String을 이용해서 풀수 있지 않을까?하고 삽질하다 결국 때려쳤다.스택을 이용하면 간단하게 풀수있다.스택이란 선입후출 구조의 자료형이다.

Stack<자료형> stack = new Stack<자료형>() 이걸로 구현하면 된다.

import java.util.*;
import java.io.*;

class Main{
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        Stack<Integer> st = new Stack<Integer>();
        int N = sc.nextInt();
        sc.nextLine();
        for(int i=0;i<N;i++){
            String str = sc.nextLine();
            st.clear();
            try{ 
                for(int j=0;j<str.length();j++){
                    if(String.valueOf(str.charAt(j)).equals("("))
                        st.push(1);
                    else
                        st.pop();
                }
            }catch(Exception e){ // ))이게 더 많을경우 에러가 발생한다.
                System.out.println("NO");
                continue;
            }
            if(st.empty()) System.out.println("YES"); // 비어있으면 개수가 딱 맞았다는 소리
            else System.out.println("NO"); // ((이게 더 많았다는 소리
        }
    }
}
profile
개발자로 취직을 희망합니다.

0개의 댓글