본문 바로가기

OJ

[SWEA] 1218 괄호 짝짓기 (JAVA)

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {

	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		String set = "()[]{}<>";
		
		for (int testCase = 1; testCase <= 10; testCase++) {
			
			br.readLine();
			String str = br.readLine();
			String temp = "";
			int result = 1;	// 끝날 때까지 1이면 정상, 0이면 비정상
			int i = 0;		// str에서의 index를 계산하기 위함
			int len = 0;	// temp의 길이를 넣을 것
			
			/* str 끝까지 알아보자 */
			while(i < str.length()) {
				
				char c = str.charAt(i);
				
				if(c == '(' || c == '[' || c == '{' || c == '<') {
					
					temp += c;
					
				} else {
					
					len = temp.length();
					
					/* temp의 길이가 0보다 크고, 
					   지금 닫으려고 하는 괄호가 temp의 마지막 괄호와 맞물리는가? */ 
					if(len > 0 && temp.charAt(len - 1) == set.charAt(set.indexOf(c) - 1)) {
						
						temp = temp.substring(0, len - 1);	// 괄호가 닫혔으니 날려보냄
					
					/* 비정상적으로 괄호를 닫으려고 하면 탈출 */
					} else {
						
						result = 0;
						break;
						
					}
					
				}
				
				i++;
				
			}
			
			sb.append("#").append(testCase).append(" ").append(result).append("\n");
			
		}
		
		System.out.print(sb);
		
	}
	
}

'OJ' 카테고리의 다른 글