코딩테스트/프로그래머스
[프로그래머스] Level 2 - 괄호 회전하기 (Python)
ye0nn
2022. 6. 9. 12:50
https://programmers.co.kr/learn/courses/30/lessons/76502
코딩테스트 연습 - 괄호 회전하기
programmers.co.kr
✅ Solution
- deque를 이용해 문자 하나씩 빼주면서 stack 가장 마지막 요소와 짝일 때, stack의 마지막 요소를 pop 해주고
- 짝이 아니라면 빼준 문자를 stack에 넣어준다.
- stack에 남아있는 문자가 없을 때 올바른 괄호 문자열임을 의미하므로 answer에 1을 더해준다.
✅ Code
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