728x90
반응형
문제 출처: https://school.programmers.co.kr/learn/courses/30/lessons/76502
첫 풀이:
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
반응형
댓글