코딩테스트/삼성 SW Expert 문제

[Java] SWEA_1218_괄호짝짓기

jaewon_sss 2021. 2. 9. 23:46
반응형
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;

public class Solution_1218_괄호짝짓기 {
	
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder output = new StringBuilder();
		StringTokenizer tokens;
		for (int t = 1; t <= 10; t++) {
			int N = Integer.parseInt(input.readLine());
			String line = input.readLine();
			int answer = 0;
			int[] spell = new int[4];
			for (int i = 0; i < spell.length; i++) {
				spell[i] = 0;
			}
			for (int n = 0; n < N; n++) {
				char c = line.charAt(n);
				if(c == '(') spell[0]++;
				else if(c == ')') spell[0]--;
				
				else if(c == '[') spell[1]++;
				else if(c == ']') spell[1]--;
				
				else if(c == '{') spell[2]++;
				else if(c == '}') spell[2]--;
				
				else if(c == '<') spell[3]++;
				else if(c == '>') spell[3]--;
			}
			for (int i = 0; i < spell.length; i++) {
				answer=1;
				if(spell[i] != 0) {
					answer = 0;
					break;
				}
				
			}
			output.append("#").append(t).append(" ").append(answer).append("\n");
		}
		System.out.println(output);

	}
}

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;

public class Solution_1218_괄호짝짓기 {
	static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
	static StringBuilder output = new StringBuilder();
	static StringTokenizer tokens;
	static int N;
	
	public static void main(String[] args) throws NumberFormatException, IOException {
		for (int t = 1; t <= 10; t++) {
			N = Integer.parseInt(input.readLine());
			Stack<Character> stack = new Stack<Character>();
			int answer = 0;
			String line = input.readLine();
			for (int n = 0; n < N; n++) {
				char c = line.charAt(n);
				if(c == ')' && stack.peek() == '(') stack.pop();
				else if(c == ']' && stack.peek() == '[') stack.pop();
				else if(c == '}' && stack.peek() == '{') stack.pop();
				else if(c == '>' && stack.peek() == '<') stack.pop();
				else stack.push(c);
			}
			System.out.println(stack);
			if(stack.isEmpty()) answer = 1;
			else answer = 0;
			output.append("#").append(t).append(" ").append(answer).append("\n");
		}
		System.out.println(output);
	}
}
반응형

'코딩테스트 > 삼성 SW Expert 문제' 카테고리의 다른 글

[Java] SWEA_1223_계산기2  (0) 2021.02.08
[Java] SWEA_9229_한빈이와spotMart  (0) 2021.02.08
[Java] SWEA_3499_퍼펙트셔플  (0) 2021.02.08
[Java] SWEA_1228_암호문1  (0) 2021.02.08
[Java] SWEA_1225_암호생성기  (0) 2021.02.08