[프로그래머스] 올바른 괄호

이찬혁·2024년 4월 9일

알고리즘

목록 보기
37/72

프로그래머스 Lv2 - 올바른 괄호 문제

프로그래머스 알고리즘 고득점 Kit 카테고리의 스택/큐 문제를 풀이했다.
스택/큐로 분류되어서 그런지 프로그래머스 IDE 풀이 공간에 큐 객체가 선언 및 초기화 되어 있었고,
여기에 나는 cnt 변수와 큐를 루프하는 while문을 추가하여 풀이했다.

문제 설명 중 "괄호가 바르게 짝지어졌다는 것은 '(' 문자로 열렸으면 반드시 짝지어서 ')' 문자로 닫혀야 한다는 뜻입니다."에 유의하여 풀이했고 사실 풀이하면서 그냥 인자로 주어진 String s를 Char 반복문을 통해도 풀이할 수 있을 것 같았다. 풀이 후에 다른 사람의 풀이를 보니 역시 그냥 Char 반복문을 통해 풀이한 사람이 더 많았다.

풀이하는 방법은 다양하고 어떤 방식이 더 성능상으로 좋은지 비교해보진 않았지만, 문제 카테고리 분류에 따라서 큐로 풀이해보았다.

CorrectParentheses.java

package com.example.Programmers.Lv2;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 프로그래머스 Lv2 - 올바른 괄호
 */
public class CorrectParentheses {
    boolean solution(String s) {
        int cnt = 0;
        Queue<Character> queue = new LinkedList<Character>();

        for (char c : s.toCharArray()) {
            queue.add(c);
        }

        while (!queue.isEmpty()) {
            Character c = queue.poll();
            if (c == '(') {
                cnt++;
            } else {
                cnt--;
            }

            if (cnt < 0) {
                return false;
            }
        }

        if (cnt == 0) {
            return true;
        } else {
            return false;
        }
    }
}

CorrectParenthesesTest.java

package com.example.Programmers.Lv2;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class CorrectParenthesesTest {
    @Test
    public void testCorrectParentheses() {

        CorrectParentheses cp = new CorrectParentheses();

        boolean result1 = cp.solution("()()");
        boolean result2 = cp.solution("(())()");
        boolean result3 = cp.solution(")()(");
        boolean result4 = cp.solution("(()(");

        assertTrue(result1);
        assertTrue(result2);
        assertFalse(result3);
        assertFalse(result4);
    }
}
profile
나의 개발로그

0개의 댓글