본문 바로가기
프로그래머스/2단계

(Python/LV2) 괄호 회전하기

by windy7271 2022. 9. 23.
728x90
반응형

문제 출처: https://school.programmers.co.kr/learn/courses/30/lessons/76502

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

첫 풀이: 


def solution(s):
    list = [i for i in s]
    list.append(list[0])
    count = 0

    for left, right in zip(list,list[1:]):
        if left == '[' and right == ']':
            count += 1
        elif left == '(' and right == ')':
            count += 1
        elif left == '{' and right == '}':
            count += 1
    return count
print(solution("}}}"))

위 방법으로는 테스트로는 통과하는데 제출하면 몇개가 틀리는데 어디서 틀리는지 정확히 몰라 데큐를 쓰기로 했다.

 

왜 틀렸는지 생각해봐야겠다 

 

from collections import deque

def isCorrect(s):
        stack = []
        s = deque(s)

        while s:
            tmp = s.popleft()
            if stack:
                if tmp == ']' and stack[-1] == '[':
                    stack.pop()
                elif tmp == '}' and stack[-1] == '{':
                    stack.pop()
                elif tmp == ')' and stack[-1] == '(':
                    stack.pop()
                else:
                    stack.append(tmp)
            else:
                stack.append(tmp)

        return True if not stack else False

def solution(s):
    answer = 0

    for i in range(len(s)):
        if isCorrect(s[i:] + s[:i]):
            answer += 1

    return answer

 

반응형

댓글