요구사항
- 시간 제한: 0.3초
- 메모리 제한: 512MB
- 명령어가 수행되기 전에 커서는 문장의 맨 뒤에 위치
- 모든 명령어를 수행하고 난 후 편집기에 입력되어 있는 문자열을 구하라.
설계
- 스택으로 풀자.
- 요구사항 3번을 보면 커서를 기준으로 왼쪽 오른쪽으로 나뉜다.
- 명령어가 실행됨에 따라 왼/오 스택에 추가하고 제거한다.
구현
import sys
input = lambda: sys.stdin.readline().rstrip()
left_stack = list(input()) # 입력 문자
command_line = int(input()) # 명령어 줄 개수
rigth_stack = []
for _ in range(command_line):
command = input()
if command[0] == "P":
left_stack.append(command[2])
elif command == "L":
if left_stack:
rigth_stack.append(left_stack.pop())
elif command == "B":
if left_stack:
left_stack.pop()
elif command == "D":
if rigth_stack:
left_stack.append(rigth_stack.pop())
rigth_stack.reverse()
print(''.join(left_stack+rigth_stack))
- commnad[1] 은 공백을 의미한다. 따라서 command[2] 를 해준다.
- if left_stack 혹은 if rigth_stack으로 pop이 가능한 지 예외처리해준다.
- 모든 명령어를 명령어를 실행한 다음 left_stack과 rigth_stack을 출력해보면 왜 reverse() 하는 지 알 수 있다.