[백준] 9012번: 괄호 (sol.1)

임정규·2024년 8월 4일
0

백준풀이

목록 보기
1/13

풀이시간: 26분

1. 나의 풀이

n = int(input())

while n > 0:
    s = []
    context = input()
    while len(context) > 0:
        top = context[0]
        if len(s) != 0 and (s[-1] == '(' and top == ')'):
            context = context.replace(context[0],'', 1)
            s.pop(-1)
        else:
            context = context.replace(context[0],'', 1)
            s.append(top)

    if len(s) == 0:
        print('YES')
    else:
        print('NO')
    n -= 1
  • 짝이 맞아야 되니 스택으로 풀이
  • 예제 입력 횟수와 문자열 길이만큼 계산을 해야하기 때문에 while문으로 작성
  • 문자열을 리스트와 비슷하게 접근할 수 있다는 것을 활용
  • replace로 문자열을 줄여가며 계산
  • 계산이후 스택의 길이를 토대로 YES or NO 출력

2. 또다른 풀이

for _ in range(int(input())):
    stk = []
    isVPS = True
    for ch in input():
        if ch == '(':
            stk.append(ch)
        else:
            if len(stk) > 0:
                stk.pop()
            else:
                isVPS = False
                break

    if len(stk) > 0:
        isVPS = False
    
    print('YES' if isVPS else 'NO')

3. 보완할 것

  • 한번에 모든 조건을 해결하려고 하지않고 나누어서 해결하려하기 → 오히려 본인 스스로 함정 파는 꼴...
  • 계산하나하나 순서대로 생각하면서 그 상황에 대한 것만 풀이하기
profile
안녕하세요.

0개의 댓글