백준 - 괄호 (9012)

Giho Kim·2023년 9월 14일

코테 연습

목록 보기
3/26

오늘은 백준

문제

입력으로 주어진 괄호 문자열이 VPS 인지 아닌지를 판단해서 그 결과를 YES 와 NO 로 나타내어야 한다.

풀이

  • stack을 하나 만들고 ( 일때 append ) 일땐 스택이 비어있는지 확인 후 pop
  • 비어있다면 print('NO') 후 break
  • break 문으로 나가진 후 바깥 else 문으로 들어감
  • 스택이 비어있다면 print('yes') 스택이 차 있다면 print('no')

느낀점

  1. 보자마자 스택 문제인거 알아냄
  2. 근데 못품 ^^
  3. 이제 return 문이면 문제없이 풀꺼같은데 print로 해야되서 좀 헷갈렸음
T = int(input())

for i in range(T):
  paren = input()
  stack = []
  
  for i in (paren):
    if i == "(":
      stack.append(i)
    elif i == ")":
      if stack:
        stack.pop()
      else:
        print("NO")
        break
  else:
    if not stack:
      print('YES')
    else:
      print('NO')

다른 풀이

t = int(input())
for _ in range(t):
  stk = []
  s = input()
  isVPS = True

  for ch in s:
      if ch == '(':
          stk.append('(')
      if ch == ')':
          if stk:
              stk.pop()
          elif not stk:
              isVPS = False
              break
  if not stk and isVPS:
      print('YES')
  elif stk or not isVPS:
      print('NO')

이게 더 참신 한거 같다.

profile
취준돌이 개발자 김기호

0개의 댓글