백준 5430번 "AC"

sanha_OvO·2021년 5월 2일
0

Algorithm

목록 보기
36/84

문제

백준 5430번 AC


풀이

시간 복잡도를 줄일 필요가 있는 문제이다.

replace()를 이용하여 R연산이 두번 연속일 경우 연산을 행하지 않도록 명령어를 고쳐야하며,
연산중 R연산이 나온다고 그때 그때 reverse()를 실행하지 않고 isReversed 불린 변수를 만들어
큐의 지금 상태가 뒤집어져 있는지, 그대로인지 판단하여 큐의 앞, 뒤 속성을 pop해준다.
이 후 isReversed의 최종값에 따라 큐를 뒤집을지 그대로 놔둘지 판단하면 된다.

error 출력은 경우, 예외처리를 이용하여 에러의 유무를 판단하면 된다.


Python 코드

import sys
from collections import deque
input = sys.stdin.readline

for _ in range(int(input())):
  command = input()
  n = int(input())
  arr = input()[1:-2].split(',')
  if n == 0:
    que = deque([])
  else:
    que = deque(arr)
  command = command.replace('RR','')
  
  check = True
  isReversed = False
  
  for a in command:
    try:
      if a == 'R':
        isReversed = not isReversed
      if a == 'D':
        if isReversed == False:
          que.popleft()
        else:
          que.pop()
    except:
      check = False
      break

  if isReversed == True:
    que.reverse()

  if check == False:
    print('error')
  else:
    print('['+ ','.join(que) +']')
profile
Web Developer / Composer

0개의 댓글