알고리즘 with python/자료구조
[자료구조] 백준 9012번 괄호 with Python
정민됴
2023. 3. 20. 16:35
https://www.acmicpc.net/problem/9012
import sys
stack = []
def push(num):
stack.append(num)
def pop():
if len(stack) == 0:
return -1
n = stack.pop()
return n
n = int(sys.stdin.readline().rstrip())
for i in range(n):
s = sys.stdin.readline().rstrip()
stack = []
for ch in s:
if ch == '(':
push(1)
if ch == ')':
result = pop()
if result == -1:
stack.append(1)
break
if len(stack) == 0:
print("YES")
else :
print("NO")
stack의 원리를 이용하면 되는 문제였다.
(가 들어오면 stack에 1을 push하고 )가 들어오면 pop을 해준다.
이 때 짝이 잘 맞는다면 push와 pop을 수행한 횟수가 같기때문에 stack의 크기는 0이 될 것이고 이 때 YES로 출력해주었다.
짝이 안맞는다면 pop을 해야하는데 아무것도 없거나(1을 임의로 넣어주고 break를 해주었다) pop이 되지 않아서 stack의 크기가 1이상일 것이고 이땐 NO로 출력하게 해주었다.