백준 1874번: 스택 수열

danbibibi·2021년 10월 2일
0

문제

문제 바로가기> 백준 1874번: 스택 수열

풀이

def solution():
    import sys
    input = sys.stdin.readline
    stack, ans = [0], []
    begin = 1
    is_no = False
    n = int(input())
    for _ in range(n):
        is_top, is_add = False, False
        num = int(input())
        if stack[-1] == num:
            is_top = True
            ans.append("-")
            del stack[-1]
        else:
            for i in range(begin, num+1):
                is_add = True
                stack.append(i)
                ans.append("+")
            del stack[-1]
            ans.append("-")
        if num+1>begin:
            begin = num+1
        if is_top==False and is_add==False: is_no = True
    if is_no:
        print("NO")
    else:
        for i in ans: print(i)
solution()

코드 개선

아래와 같이 작성함으로써 불필요한 변수를 제거하고, 더 이해하기 쉽게 작성할 수 있다.

def solution():
    import sys
    input = sys.stdin.readline
    n, top, is_no = int(input()), 1, False
    stack, ans = [], []
    for _ in range(n):
        num = int(input())
        while top <= num:
            stack.append(top)
            ans.append('+')
            top += 1
        if stack[-1] != num:
            is_no = True
        stack.pop()
        ans.append('-')
    if is_no: print("NO")
    else:
        for i in ans: print(i)
solution()
profile
블로그 이전) https://danbibibi.tistory.com

0개의 댓글

관련 채용 정보