문제10 [스택] 괄호 회전하기

반응형

https://wikidocs.net/223104

def solution(s):
  answer=0
  n=len(s)
  for i in range(n):
    stack=[]
    # 괄호 문자열을 회전시키면서 참조
    for j in range(n):
      c = [s(i + j) % n]
      if c in '([{': # 열린 괄호는 푸시
        stack.append(c)
      else:
        if not stack: # 짝이 맞지 않는 경우
          break
          
        # 닫힌 괄호는 스택의 top과 짝이 맞는지 비교
        if c == ")" and stack[-1] == "(":
          stack.pop()
        elif c == "]" and stack[-1] == "[":
          stack.pop()
        elif c == "}" and stack[-1] == "{":
          stack.pop()
        else:
          break
    else:
      if not stack:
        answer += 1
  return answer

 

- 스택으로 짝을 찾으면서 횟수를 누적한다.

 

반응형