[백준] 1874번(스택 수열)

·2023년 5월 1일

백준 문제풀이

목록 보기
56/159

백준 1874번


최종 제출 코드

n = int(input().rstrip())

arr = [] #입력값 받는 배열
stack = [] #1~n까지 숫자 push, pop하는 스택
sign = []

for i in range(n):
  ele = int(input().rstrip())
  arr.append(ele)

index = 0

for j in range(1, n+1):
  stack.append(j)
  sign.append('+')

  while stack[len(stack)-1] == arr[index]:
    stack.pop()
    sign.append('-')
    index += 1
    if index == n or len(stack)==0:
      break

if len(stack) != 0:
  print("NO")
else:
  for i in sign:
    print(i)

◼ 리스트의 마지막 원소 얻는 방법

  • while문의 조건에 stack[len(stack)-1]를 포함했더니 stack의 길이가 0인 경우는 IndexError 발생
    stack[-1]으로 작성하면 해결!
profile
백엔드 개발자가 되고 싶어요(22.8.15~)

0개의 댓글