[알고리즘] 인프런 - 올바른 괄호

정은아·2024년 1월 10일
post-thumbnail

인프런 - 자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비

- Section 5 - 올바른 괄호 문제

틀렸던 풀이

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

public class Stack_01 {
	public static void main(String[] args) {
		// 올바른 ()쌍으로 끝나면 YES, 아니면 NO

		// 1. 테스트케이스 String을 받는다
		// 2. 답을 출력할 answer변수를 만든다.
		// 3. stack을 만든다.
		// 4. forEach문을 돌려서 값을 채운다.
		// 5. if문을 써서 '('면 stack에 add해준다.
		// 6. '('가 아니라면 remove해주는데,
		// stack이 비어있다면 바로 answer를 NO로 바꿔 출력한다.
		// 7. 모든 값을 stack에 넣었는데 stack이 비어있지 않다면 NO

		Scanner sc = new Scanner(System.in);

		String str = sc.next();
		String answer = "YES";

		Stack<Character> stack = new Stack<>();

		for (char ch : str.toCharArray()) {
			if (ch == '(') {
				stack.add(ch);
			} else {
				if (stack.isEmpty()) {
					answer = "NO";
					break;
				} else {
					stack.pop();
				}
			}
			if (!stack.isEmpty()) {
				answer = "NO";
			}
		}
		

		System.out.println(answer);
	}
}

정답(내풀이)

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

public class Stack_01 {
	public static void main(String[] args) {
		// 올바른 ()쌍으로 끝나면 YES, 아니면 NO

		// 1. 테스트케이스 String을 받는다
		// 2. 답을 출력할 answer변수를 만든다.
		// 3. stack을 만든다.
		// 4. forEach문을 돌려서 값을 채운다.
		// 5. if문을 써서 '('면 stack에 add해준다.
		// 6. '('가 아니라면 remove해주는데,
		// stack이 비어있다면 바로 answer를 NO로 바꿔 출력한다.
		// 7. 모든 값을 stack에 넣었는데 stack이 비어있지 않다면 NO

		Scanner sc = new Scanner(System.in);

		String str = sc.next();
		String answer = "YES";

		Stack<Character> stack = new Stack<>();

		for (char ch : str.toCharArray()) {
			if (ch == '(') {
				stack.add(ch);
			} else {
				if (stack.isEmpty()) {
					answer = "NO";
					break;
				} else {
					stack.pop();
				}
			}
		}
		
		if (!stack.isEmpty()) {
			answer = "NO";
		}

		System.out.println(answer);
	}
}

GPT 풀이

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

public class BalancedParentheses {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String input = sc.next();
        String answer = checkBalancedParentheses(input);
        System.out.println(answer);
    }

    private static String checkBalancedParentheses(String str) {
        Stack<Character> stack = new Stack<>();

        for (char ch : str.toCharArray()) {
            if (ch == '(') {
                stack.push(ch);
            } else if (ch == ')') {
                if (stack.isEmpty() || stack.pop() != '(') {
                    return "NO"; // Unbalanced parentheses encountered
                }
            }
        }

        if (stack.isEmpty()) {
            return "YES"; // Balanced parentheses
        } else {
            return "NO"; // Unbalanced parentheses at the end
        }
    }
}

느낀점

또!!!!!!! 또 중괄호를 또!!!!!!!!!!!!!!! 하 내가 너무 밉다 잔뜩 약이 올라서 GPT한테도 물어봤는데 GPT도 자꾸 틀린답만 내놔서 너무 약이 올랐다. 근데 또 실수였다. 이러면 곤란해!!!! 반성한다. 마지막 if문은 for문 끝나고 쓰는건데.. 그렇게 설계해놓고 바보같이 또!!!!!!!!!!!

profile
꾸준함의 가치를 믿는 개발자

0개의 댓글