백준/스택

괄호 - Java

연구하는개발자 2021. 3. 23. 13:16
728x90

www.acmicpc.net/problem/9012

 

9012번: 괄호

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

www.acmicpc.net

class Main {

    static Boolean isVPS(String s){
        Stack<Character>st = new Stack<>();

        if(s.length()>0) {
            st.push(s.charAt(0));
        }
        for(int idx =1 ; idx<s.length();idx++ ){

            if(st.isEmpty()){st.push(s.charAt(idx));continue;}
            Character top = st.peek();
            char ch = s.charAt(idx);
            if(ch==')'){

                if(top=='('){
                    st.pop();
                }
                else{
                    st.push(ch);
                }
            }
            else{
                st.push(ch);
            }
        }

        return st.isEmpty();

    }


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

       // int n;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       // StringTokenizer st = new StringTokenizer(br.readLine());
        int n= Integer.parseInt(br.readLine());



         //   String[] inputList = new String[n];
            String line = "";
            for (int i = 1; (line =br.readLine())!=null; i++) {


                if (!isVPS(line)) {
                    System.out.println("NO");
                } else {
                    System.out.println("YES");
                }
            }
            br.close();

    }



}