• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

쇠막대기 오답 질문

23.10.12 10:10 작성 23.10.12 10:10 수정 조회수 108

0

닫는 괄호를 만날 때마다 count++를 해주는 방식은 왜 정답이 안나오는 지 알 수 있을까요?

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

public class Main {
    public static int solution(String str){
        int answer = 0;
        char[] strTochars = str.toCharArray();
        Stack<Character> stack = new Stack<>();
        int count = 0;

        for (int i=0; i<strTochars.length; i++) {
            if (strTochars[i] == '(') stack.push('(');
            else {
                if (!stack.isEmpty() && stack.peek() == '(') {
                    stack.pop();
                    count ++;
                    if (i>0 && strTochars[i-1] != '(') { // 막대
                        answer += count;
                        count = 0;
                    }
                }    
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        System.out.println(solution(str));
    }
}

 

답변 1

답변을 작성해보세요.

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.10.14

안녕하세요, 인프런 AI 인턴이에요.

제가 보았을 때, 코드는 충분히 정확해 보입니다. 그러나 답이 나오지 않는 이유는 count 변수를 잘못 처리했기 때문입니다.

주어진 코드에서는 막대기의 길이를 구하는 것이 목적인 것으로 보입니다. 막대기가 끝날 때마다 count 변수를 0으로 초기화하여 다음 막대기의 길이를 구합니다. 하지만 현재 코드에서는 닫는 괄호를 만날 때마다 count 변수를 초기화하고 있습니다.

따라서, 막대기의 길이를 구하기 위해서는 닫는 괄호를 만났을 때 count 변수를 초기화하는 것이 아니라, 열리는 괄호를 만났을 때 count 변수를 초기화해야 합니다.

아래의 코드를 참고해보세요.

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

public class Main {
    public static int solution(String str){
        int answer = 0;
        char[] strTochars = str.toCharArray();
        Stack<Character> stack = new Stack<>();
        int count = 0;

        for (int i=0; i<strTochars.length; i++) {
            if (strTochars[i] == '(') {
                stack.push('(');
                count = 0; // 열리는 괄호를 만나면 count 변수를 초기화
            }
            else {
                if (!stack.isEmpty() && stack.peek() == '(') {
                    stack.pop();
                    count ++;
                    if (i>0 && strTochars[i-1] != '(') { // 막대
                        answer += count;
                    }
                }    
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        System.out.println(solution(str));
    }
}

이렇게 수정하면, 막대기의 길이를 올바르게 구할 수 있을 거예요. 그럼 원하시는 결과를 얻을 수 있도록 도움이 되었길 바랄게요. 더 궁금한 점이 있으면 언제든지 물어보세요. 좋은 하루 되세요.