<JAVA>백준 9012번 괄호

eunsiver·2022년 9월 1일
0

<JAVA>백준 알고리즘

목록 보기
3/11
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Stack;

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(System.out));

		int n = Integer.parseInt(br.readLine());
		Stack<Character> stack = new Stack<>();
		String an = "YES\n";
		while (n-- > 0) {
			String st = br.readLine() + "\n";
			for (char ch : st.toCharArray()) {
				if (ch == '\n') {
					if (!stack.isEmpty()) {
						an = "NO\n";
						stack.clear();
					}

				} else if (ch == ')') {
					if (stack.isEmpty()) {
						an = "NO\n";
						stack.clear();
						break;

					} else {
						stack.pop();
					}
				} else {
					stack.push(ch);
				}

			}
			wr.write(an);
			an = "YES\n";
		}
		wr.flush();
	}
}
  1. ')' 일때, 끄낼게 없으면 N, 있으면 pop
  2. 마지막에 '('가 남아있으면 N
  3. 그 외 push
profile
Let's study!

0개의 댓글