[백준(Baekjoon)][자바(java)] 4949 : 균형잡힌 세상 / 스택

728x90

 

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

 

4949번: 균형잡힌 세상

하나 또는 여러줄에 걸쳐서 문자열이 주어진다. 각 문자열은 영문 알파벳, 공백, 소괄호("( )") 대괄호("[ ]")등으로 이루어져 있으며, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마

www.acmicpc.net

 

import java.util.Scanner;
import java.util.Stack;

public class Main {
	
	public static boolean isCorrect( String s ) {
		Stack<Character> stack = new Stack<>();
		int len = s.length(), i;  char c, p;
		for( i = 0; i < len; i++ ) {
			c = s.charAt( i );
			if( c == '(' ||  c == '[' ) {
				stack.add( c );
				continue;
			}
			p = stack.empty() ? ' ' : stack.peek();
			if( c == ')' ) {
				if( p == '(' )	 stack.pop();
				else		 	 return false;
			}
			if( c == ']' ) {
				if( p == '[' )	 stack.pop();
				else		 	 return false;
			}
		}
		if( stack.empty() )				
			return true;
		return false;
	}

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		String s = "", t = "";
		StringBuilder ss = new StringBuilder();
		StringBuilder res = new StringBuilder();
		loop:
		while( true ) {
			while( true ) {
				t = sc.nextLine();
				ss.append( t );
				if( t.equals(".") )
					break loop;
				if( t.charAt( t.length()-1 ) == '.' )
					break;
			}
			s = ss.toString();
			ss.setLength(0);
			res.append( ( isCorrect( s ) ? "yes" : "no" ) + "\n" );
		}
		sc.close();
        
        System.out.println( res.toString() );

	}
}

 

- 한 줄씩 입력 받음
- 마지막 글자가 . 일 때까지 입력받음
- 모두 한 문자열에 합침
- 총 합친 문자열이 "." 이면 종료, 그렇지 않으면 한 글자씩 검사하며 괄호 찾기

- '(' or '[' 일 경우 스택에 PUSH
- ')' or ']' 일 경우, 스택이 비어있지 않으며 스택의 top이 '(' 나 '[' 일 때 top을 지움
  ( 괄호가 균형잡힌 한 쌍을 이루므로 ) 
- 문자열의 모든 글자를 검사 후 스택이 비어있으면 균형잡힌 괄호이므로 yes, 그렇지 않으면 no 출력

 

 

반응형