미소를뿌리는감자의 코딩

[백준 2024/01/19] 4949번 균형잡힌 세상 본문

코딩 테스트/백준

[백준 2024/01/19] 4949번 균형잡힌 세상

미뿌감 2024. 1. 19. 19:23
728x90

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

 

4949번: 균형잡힌 세상

각 문자열은 마지막 글자를 제외하고 영문 알파벳, 공백, 소괄호("( )"), 대괄호("[ ]")로 이루어져 있으며, 온점(".")으로 끝나고, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마지막에

www.acmicpc.net

 

1. 접근 방법

이 문제는 보자마자, ()[]. 을 분리해 내야겠다고 생각이 들었다.

사실 알파벳 같은 경우에는, 따로 고려해야할 부분이 없다고 생각하였기 때문이다.

rough draft

 

 

따라서 ChatGPT 에서 예시문장을 주고, ()[]. 을 분리해 낼 방법을 물어보았다.

Pattern 및 matcher class를 사용하면 될 것이라고 하였다.

 

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Pattern pattern = Pattern.compile("[\\[\\]()\\.]");

String line = reader.readLine();

Matcher matcher = pattern.matcher(line);
Stack<String> stack = new Stack<>();


while(matcher.find()){
      stack.push(matcher.group());
}

 

이후, 새로 분리해낸 문장의 경우 ()[]. 이런식으로 생기게 되고,

 

.을 제외한 나머지는 stack에 넣었다.

.의 경우, 맨 뒤에 .이 있는지 유무를 먼저 따지고, 없다면 no를 출력, 

있지만, 길이가 1이라면 프로그램을 종료 시켰다.

 

이제 stack에서 하나씩 꺼내며 값을 비교해 줄 것이다.

1) 만약 ] 또는 )이 pop 되었다면, 다른 stack에다가 넣어주었다.

 

2) [ or ( 이 pop 되었다면, 다른 stack에 넣어준 값을 pop 하고, 두 값이 () or []로 잘 짝이 만들어지는 지 확인하였다.

 

이 문제의 경우, 나의 프로그램으로 돌렸을 때, 아무 문제가 되지 않았지만,

백준에서 정답을 맞히려고 하면 런타임 에러( EmptyStack + NosuchElement) 에러가 발생 하였다.

 

EmptyStack의 경우 peek() 이나 pop()을 시행하기 전에 stack 이 비었는지 유무를 확인하여 해결해 주었지만,

NosuchElement에러의 경우 이유를 잘 알지 못했다. 

아무리 보아도, 코드에 틀린 부분이 없었다.. 그래서 백준에서 제공하는 NoSuchElement 설명에 대한 파일을 확인했다.

 

https://help.acmicpc.net/judge/rte/NoSuchElement

 

런타임 에러 (NoSuchElement)

ScannerScanner에서 이 에러가 발생하는 경우는 더 이상 입력받을 수 있는 값이 없을 때 입니다.import java.util.*; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); in

help.acmicpc.net

해당 부분을 보니, Scanner에 대한 언급이 있어

설마 하고 받아들이는 것을 scanner 대신 BufferedReader를 이용하였다.

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

 

그랬더니.. 마법 같이 문제가 해결되고, 문제를 맞힐 수 있었다.

 

앞으로 Scanner의 사용을 조금 지양하는 것이 좋겠다는 생각이 들었다.

백준의 경우 Scanner가 나의 프로그램에서 작동하는 것처럼 작동이 안되는 것 같은 느낌이다.

 

코드가 뭔가 난잡한 느낌이 있어서, 추후에 잘 정리해보길 바란다..

(오늘을 컨디션 난조로 어려울 것 같다..ㅠ 감기 조심하세요들..)

 

2. 코드

import java.util.Objects;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class b4949 {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        Pattern pattern = Pattern.compile("[\\[\\]()\\.]");

        while (true) {
            String line = reader.readLine();

            Matcher matcher = pattern.matcher(line);
            Stack<String> stack = new Stack<>();


            while(matcher.find()){
                stack.push(matcher.group());
            }

            if(stack.isEmpty()){
                System.out.println("no");
            }
            else{
                if(Objects.equals(stack.peek(), ".")){
                    if(line.length()==1){
                        break;
                    }
                    else{
                        stack.pop();
                        if(parenthesis(stack)){
                            System.out.println("yes");
                        }
                        else{
                            System.out.println("no");
                        }
                    }
                }
                else{
                    System.out.println("no");
                }
            }

        }
    }
    public static boolean parenthesis(Stack<String> orig_stack){
        Stack<String> another_stack = new Stack<>();
        while(!orig_stack.isEmpty()){
            if(Objects.equals(orig_stack.peek(), "]") || Objects.equals(orig_stack.peek(), ")")){
                another_stack.push(orig_stack.pop());
            }
            else{
                if(another_stack.isEmpty()){
                    return false;
                }

                if(Objects.equals(orig_stack.pop(), "[")){
                    if(!Objects.equals(another_stack.pop(), "]")){
                        return false;
                    }
                }
                else{
                    if(!Objects.equals(another_stack.pop(),")")){
                        return false;
                    }
                }
            }
        }
        return another_stack.isEmpty();

    }
}
728x90