프로그래밍/Algorithm

프로그래머스 괄호 회전하기

모지사바하 2022. 1. 20. 15:38

https://programmers.co.kr/learn/courses/30/lessons/76502

 

코딩테스트 연습 - 괄호 회전하기

 

programmers.co.kr

 

이 문제는 보자마자 떠오르는대로 풀면 간단히 풀릴거라 예상했고 실제로 떠오른대로 푸니 간단했다.

 

하지만 이 문제는 얼마든지 더 간단한 규칙을 찾을 수 있을 것 같다는 생각이 든다..

 

내가 푼 풀이는 그저 주어진 문자열의 길이만큼 문자를 한칸씩 이동하며 올바른 괄호 문자열인가 검사하고 맞다면 정답에 +1 을 해주는것이다.

 

다른사람의 풀이에 훨씬 간단한 규칙을 찾아서 푼 고수분들이 계실거라 기대하며 봤지만 내가 푼 풀이와 동일했다.

 

from collections import deque


def solution(s):
    answer = 0

    if len(s) % 2 == 1:
        return 0

    temp = deque([x for x in s])

    for i in range(len(s)):
        if i > 0:
            temp.append(temp.popleft())

        if is_perfect(''.join(temp)):
            answer += 1
    return answer


def is_perfect(s):
    o = '[({'
    c = '])}'
    if s[0] in c:
        return False

    d = deque([x for x in s])
    st = [d.popleft()]

    while d:
        ch = d.popleft()
        if not st and ch in c:
            return False

        if ch in o:
            st.append(ch)
        else:
            ob = st.pop()
            ob_index = o.index(ob)
            cb_index = c.index(ch)
            if ob_index != cb_index:
                return False

    return len(st) == 0


print(solution('}]()[{'))
# s     	result
# "[](){}"	3
# "}]()[{"	2
# "[)(]"	0
# "}}}"	    0