얼렁뚱땅 JAVA 문제풀이

[JAVA 백준 문제풀이] 얼렁뚱땅 9012 괄호 풀이

MOSTAR 2023. 3. 3. 10:32

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

 

9012번: 괄호

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

www.acmicpc.net

 

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

public class Main {

	public static void main(String[] args) throws IOException{
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		for(int i=0;i<n;i++) {
			Stack<String> st = new Stack<String>();
			String [] str = br.readLine().split("");
			String answer = "YES";
			for(int j=0;j<str.length;j++) {
				if (st.isEmpty()) {
					if(str[j].equals("(")) {
						st.push(str[j]);
					} else {
						answer = "NO";
						break;
					}
				}else {
					String temp = st.pop();
					if(str[j].equals("(")) {
						st.push(temp);
						st.push(str[j]);
					} 
				}
			}
			if (st.isEmpty()==false) {
				answer = "NO";
			}
			System.out.println(answer);
		}
	}

}