백준 9012

justhaza.log·2023년 3월 29일

알고리즘: BOJ

목록 보기
3/125

문제

https://www.acmicpc.net/problem/9012

코드

import sys

T = int(sys.stdin.readline())

for _ in range(T):
    parentheses = sys.stdin.readline().rstrip()
    
    check_list = []
    flag = True
    
    for parenthesis in parentheses:
        if parenthesis == "(":
            check_list.append("(")
        else:
            if len(check_list) >= 1:
                check_list.pop()
            else:
                flag = False
                
                break
            
    if len(check_list) >= 1 or flag == False:
        print("NO")        
    elif flag == True:
        print("YES")

처음에는 flag == False인 경우만 NO에 해당된다고 생각했다. 그런데 check_list에 '('가 ')'보다 많이 포함된 경우, 두 번째 for문-else에 걸리지 않고 flag == True인 채로 for문을 빠져나온다. 따라서 flag == True이더라도, len(check_list) >= 1인 경우도 NO를 출력해줘야 한다.

그리고 파이썬에서 '!False'라는 것은 존재하지 않는다. 'not False'라고 써야 한다.

아래는 다른 사람의 풀이를 보다가 check_list, flag 없이 숫자 계산으로 풀었길래 그러한 방법으로 작성해본 코드이다.

import sys

T = int(sys.stdin.readline())

for _ in range(T):
    parentheses = sys.stdin.readline().rstrip()
    sum = 0
    
    for parenthesis in parentheses:
        if parenthesis == "(":
            sum += 1
        elif parenthesis == ")":
            sum -= 1
            
        if sum < 0:
            print("NO")
        
            break
        
    if sum > 0:
        print("NO")        
    elif sum == 0:
        print("YES")

기타

profile
알고리즘이나 SQL 문제 풀이를 올리고 있습니다. 피드백 환영합니다!

0개의 댓글