[백준] 1406 에디터

파이톨치·2022년 8월 9일
0

백준

목록 보기
6/12

코드

시간 초과

import sys

# 입력 받기
s = input()
n = int(sys.stdin.readline())
cursor = len(s) 

# 명령어
for i in range(n):
  c = sys.stdin.readline().split()
  command = c[0]
  
  if command == "L" and cursor > 0:
    cursor -= 1
  if command == "D" and cursor <= len(s):
    cursor += 1
  if command == "B" and cursor > 0:
    s = s[:cursor-1] + s[cursor:]
    cursor -= 1
  if command == "P":
    s = s[:cursor] + c[1] + s[cursor:]
    cursor += 1

# 출력
print(s)

시간 초과 이유 : 솔직히 보기도 편하고 효율적인 것 같아 보이는데 슬라이싱 하는데 시간이 꽤 걸려서 안되는거 같다.

올바른 코드

import sys

# 입력 받기
left = list(input())
right = []
n = int(input())

# 명령어
for i in range(n):
  c = sys.stdin.readline().split()
  command = c[0]
  
  if command == "L" and left:
    right.append(left.pop())
  if command == "D" and right:
    left.append(right.pop())
  if command == "B" and left:
    left.pop()
  if command == "P":
    left.append(c[1])

# 출력
print(''.join(left + list(reversed(right))))

해결 방법 : 위 코드랑 사실 구조는 비슷한데 리스트를 2개 썼다는 점이 다르다.

이번엔 시간 복도를 다 O(1)로 줄였다.

리스트가 2개라 넣고 뺄 때 바로 앞에 리스트에 빼거나 추가하며 되기 때문이다.

참고 자료

https://wikidocs.net/17

문제 링크

https://www.acmicpc.net/problem/1406

profile
안알랴줌

0개의 댓글