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개라 넣고 뺄 때 바로 앞에 리스트에 빼거나 추가하며 되기 때문이다.