[알고리즘] 백준 4949 : 균형잡힌 세상 -S4

eternal moment·2023년 5월 17일
0

2023.04.26 풀이

import sys

while True:
    string = sys.stdin.readline().rstrip()
    stack = list()

    if string == '.':
        break

    for x in string:
        if x == '(':
            stack.append(x)
        elif x == ')':
            if stack and stack[-1] == '(':
                stack.pop()
            else:
                stack.append(x)
                break
        elif x == '[':
            stack.append(x)
        elif x == ']':
            if stack and stack[-1] == '[':
                stack.pop()
            else:
                stack.append(x)
                break
    if stack:
        print('no')
    else:
        print('yes')

2023.05.17 풀이

import sys
input=sys.stdin.readline

while True:
    arr=[]
    s=input().rstrip()
    res='yes'
    if s[0]=='.':
        break
    
    for i in s:
        if i =="(" or i=="[":
            arr.append(i)
        elif i==")":
            if len(arr)>=1 and arr[-1]=="(":
                arr.pop()
            else:
                res='no'
                break
        elif i=="]":
            if len(arr)>=1 and arr[-1]=="[":
                arr.pop()
            else:
                res='no'
                break
    if len(arr)!=0 or res=='no':
        print('no')
    else:
        print('yes')
  • arr=['(', '('] 과 같은 경우 때문에 마지막에서 if len(arr)!=0 이라는 조건이 필요함
  • input().split() 을 하면 공백이 제거되고 담기기때문에 예제7 과 같은 경우는 종료조건이 되어버리므로 split을 넣어주면 안됨
  • ] 와 ) 이 입력된 경우 arr의 마지막이 어떤지 따지기 전에 arr이 빈 배열인지 확인해야함

check point

  • 배열에서 마지막 인덱스를 제거 : arr.pop() == arr[:-1]
  • arr[::-1] 은 배열 뒤집기

0개의 댓글