본문 바로가기
Algorithm

[알고리즘] 괄호 백준 9012 (Python)

by 가영리 2022. 1. 14.
728x90

Stack을 pop 했을 때 top의 값이 감소하는 것을 이용하여 풀었습니다.

 

코드

import sys
n = int(sys.stdin.readline())

for i in range(n) :

  stack = sys.stdin.readline()

  top = 0

  for j in stack:
    if j == '(' :
      top += 1
    elif j == ')' :
      top -= 1
    if top < 0 :
      print('NO')
      break
  
  if top > 0 :
    print('NO')
  elif top == 0:
    print('YES')

 

입출력