https://programmers.co.kr/learn/courses/30/lessons/76502
✅ 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
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] Level 2 - 게임 맵 최단거리 (Python) (0) | 2022.06.09 |
---|---|
[프로그래머스] Level 2 - 배달 (Python) (0) | 2022.06.09 |
[프로그래머스] Level 2 - 짝지어 제거하기 (Python) (0) | 2022.06.04 |
[프로그래머스] Level 2 - 타겟 넘버 (Python) (0) | 2022.06.04 |
[프로그래머스] Level 2 - 더 맵게 (Python) (0) | 2022.06.03 |