algorithm/Python
[프로그래머스 코딩테스트 연습] 괄호 회전하기 (Python3)
wingbeat
2025. 1. 20. 04:27
반응형
https://school.programmers.co.kr/learn/courses/30/lessons/76502
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
# 리팩토링 전
def solution(s):
result = 0
for _ in range(len(s)):
s = s[1:] + s[0]
stack = []
for c in s:
if c in '({[': stack.append(c)
else:
if not stack: break
if c==')' and stack[-1]=='(':
stack.pop()
elif c=='}' and stack[-1]=='{':
stack.pop()
elif c==']' and stack[-1]=='[':
stack.pop()
else: # 정상적으로 종료시 실행
if not stack: result += 1
return result
내가 짠 버전은 문자열을 s[1:]+s[0]으로 반복하면서 검사하는 코드.
파이썬을 몇년을 했는데 for-else를 몰랐어서 창피하다.
for문이 정상 종료되면 실행되는 역할을 한다. 중간에 break로 강제종료되면 else는 실행안됨
# 리팩토링
from collections import deque
def solution(s):
result = 0
s = deque(s)
for _ in range(len(s)):
stack = []
for c in s:
if c in '({[': stack.append(c)
else:
if not stack: break
if (c==')' and stack[-1]=='(') or (c=='}' and stack[-1]=='{') or (c==']' and stack[-1]=='['):
stack.pop()
else:
if not stack: result += 1
s.rotate(-1)
return result
deque의 rotate(-1)라는 신박한 기능을 발견했다.
rotate(1) : 오른쪽으로 회전, rotate(-1) : 왼쪽으로 회전
반응형