SWEA 1218かっこ



スタックで閉じた括弧の値を入力すると、pop()を使用したときに表示される括弧とペアになります.
import java.util.Stack;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

public class Solution {
	static BufferedReader br;
	static BufferedWriter bw;
	static StringTokenizer st;
	static boolean Answer;
	static Stack<Character> stk;


	static char[] input;

	static void PushnPop() {
		
		for (int i = 0; i < input.length; i++) {
			if(input[i] == '(' || input[i] == '[' || input[i] == '{' ||input[i] == '<') {
				stk.push(input[i]);
			}else {
				if(stk.isEmpty()) {
					Answer = false;
					return;
				}
				if(input[i] == ')') {
					if(stk.pop() != '(') {
						Answer = false;
						return;
					}
				}else if(input[i] == '}') {
					if(stk.pop() != '{') {
						Answer = false;
						return;
					}
				}else if(input[i] == ']') {
					if(stk.pop() != '[') {
						Answer = false;
						return;
					}
				}else if(input[i] == '>') {
					if(stk.pop() != '<') {
						Answer = false;
						return;
					}
				}
			}
		}
		
		if(!stk.isEmpty()) {
			Answer = false;
		}
		
		
	}

	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		bw = new BufferedWriter(new OutputStreamWriter(System.out));
		int T = 10;
		for (int tc = 1; tc <= T; tc++) {
			Answer = true;
			stk = new Stack<>();
			br.readLine(); // 값 개수 버리기.
			input = br.readLine().toCharArray();
		
			PushnPop();
			bw.write(String.format("#%d ", tc));
			if (Answer) {
				bw.write("1\n");
			} else {
				bw.write("0\n");
			}
		}
		bw.flush();
		bw.close();
	}
}