최대 1 분 소요

문제 링크

내 풀이

from collections import deque 
def solution(s):
    gwals = '[({'
    turn = 0
    result = 0
    s = deque(s)
    while turn < len(s):
        a = 0
        gwal_list = []
        s.rotate(-1)
        for gwal in s:
            if gwal in gwals:
                gwal_list.append(gwal)
            else:
                if gwal_list:
                    if gwal_list[-1] == '(' and gwal == ')':
                        gwal_list.pop()
                    elif gwal_list[-1] == '{' and gwal == '}':
                        gwal_list.pop()
                    elif gwal_list[-1] == '[' and gwal == ']':
                        gwal_list.pop()
                    else:
                        a = 1
                        break
                else:             
                    a = 1
                    break
        if a == 0 and not gwal_list:
            result += 1
        turn += 1
        
    return result         

풀이 해석

  • s를 for문을 돌면서 ‘({[’ 안에 있을 경우에만 append하고 그 외엔 리스트 index -1 위치의 원소를 확인하고 비교하는 방식으로 진행하였다
  • for문을 돈 뒤엔 rotate를 진행하였다

중요 point

  • deque의 rotate 기능
  • 놓치는 예외 조건없이 코드로 표현하기

댓글남기기