다음 규칙을 지키는 문자열을 올바른 괄호 문자열이라고 정의합니다.
(), [], {} 는 모두 올바른 괄호 문자열입니다.
| s | result |
|---|---|
| "[ ] ( ) { }" | 3 |
| " } ] ( ) [ {" | 2 |
| "[ ) ( ]" | 0 |
| "} } }" | 0 |
def solution(s):
answer = 0
k = list(s)
for i in range(len(s)):
stack = []
for j in k:
if len(stack) == 0 or j == '{' or j == '(' or j == '[':
stack.append(j)
if (j == '}' and '{' not in stack) or (j == ']' and '[' not in stack) or (j == ')' and '(' not in stack):
stack.append(-1)
break
if stack[-1] == '{' and j == '}':
stack.pop()
elif stack[-1] == '[' and j == ']':
stack.pop()
elif stack[-1] == '(' and j == ')':
stack.pop()
k.append(k[0])
del k[0]
if len(stack) == 0:
answer += 1
return answer
이번 문제는 stack을 이용하여 구현했다.
코드가 복잡하고 지저분하다. 나중에 다시 풀었을 때 깔끔하고 보기 좋게 짤 수 있도록 노력해야겠다.