[실버4] BOJ4949 균형잡힌 세상

junjeong·2025년 11월 3일
0

백준 문제풀이

목록 보기
8/15
post-thumbnail

문제 분석

. 를 만나면 끝나는 문자열에서 []와 ()의 쌍이 잘 이루어져 있는가?
그렇다면 yes 아니라면 no를 출력하라.

손으로 풀기

  • 문자열 .를 만날 때까지 검사를 반복
  • (를 만났는데, 다음 특수문자가 )가 아니면 no 출력
  • [ 를 만났는데, 다음 특수문자가 ] 가 아니어도 no 출력
  • . 를 만났는데 temp에 특수문자(( 또는 [ 밖에 없을듯?) 가 남아있어도 no 출력
  • temp에 아무런 특수문자가 없는데 ] 또는 )를 만나도 no 출력

Sudo Code

Bufferreader br;
String input = br.readline();
Stack<Character> stack;

if(input이 "."랑 일치하지 않으면) {
	for(string을 순회하며, .을 만날때까지) {
		// 예외 처리 
		(stack이 비었는데 c가 ")" 또는 "]" 이면) "no" 출력하고 break;
		("."를 만났는데 stack에 요소가 존재하다면) "no" 출력하고 break;
		(stack에 요소가 "("인데 "]"를 만난다면) "no" 출력하고 break;
		(stack에 요소가 "["인데 ")"를 만난다면) "no" 출력하고 break;
		
		(c가 "(" 또는 "["일 때에만 && 스택이 비어지거나 같은 요소일 때에만) stack.push(c);
		
		(stack에 요소가 "("인데 c가 ")"라면) stack.pop();
		(stack에 요소가 "["인데 c가 "]"라면) stack.pop();
	}	
	main(); // main 재귀 호출 
}

if(input이 "."이 맞다면) 시스템 종료 -> 재귀 탈출

Code

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

public class BOJ4949 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String text = br.readLine();

        while(!text.equals(".")){
            Stack<Character> stack = new Stack<>();
            boolean result = true;
            char[] textToChar = text.toCharArray();

            for(char now : textToChar){
                if(now == '('){
                    stack.push(now);
                }else if(now == '['){
                    stack.push(now);
                }else if(now == ')'){
                    if(stack.isEmpty()){
                        result = false;
                        break;
                    }
                    char check = stack.pop();
                    if(check != '(') {
                        result =false;
                        break;
                    }
                }else if(now == ']'){
                    if(stack.isEmpty()){
                        result = false;
                        break;
                    }
                    char check = stack.pop();
                    if(check != '[') {
                        result =false;
                        break;
                    }
                }
            }
            if(result && stack.isEmpty()){
                System.out.println("yes");
            }else {
                System.out.println("no");
            }
            text = br.readLine();
        }

    }
}
profile
Whether you're doing well or not, just keep going👨🏻‍💻🔥

0개의 댓글