def solution(s):
answer = 0
s = deque(s)
for _ in range(len(s)-1):
answer += check(s)
s.append(s.popleft())
return answer
큐가 올바른 괄호 시퀀스인지 검사하는 함수
input: 큐
output: Boolean
def check(s):
q = deque([x for x in s])
stack = []
pair = {']':'[', '}':'{', ')':'('}
while q:
cur = q.popleft()
if cur in pair and stack and stack[-1] == pair[cur]:
stack.pop()
else:
stack.append(cur)
if stack:
return 0
return 1
파라미터 s를 그대로 사용하지 않고 q로 재할당 해준 이유는 아래 포스팅을 참고
https://velog.io/@happyyeon/Python-깊은-복사-얕은-복사
from collections import deque
def check(s):
q = deque([x for x in s])
stack = []
pair = {']':'[', '}':'{', ')':'('}
while q:
cur = q.popleft()
if cur in pair and stack and stack[-1] == pair[cur]:
stack.pop()
else:
stack.append(cur)
if stack:
return 0
return 1
def solution(s):
answer = 0
s = deque(s)
for _ in range(len(s)-1):
answer += check(s)
s.append(s.popleft())
return answer