처음 제출한 코드
import sys
input = sys.stdin.readline
sentence = input().rstrip()
cursor_index = len(sentence)
n = int(input().rstrip())
for i in range(n):
command = input().rstrip()
if command == 'L':
if cursor_index != 0:
cursor_index -= 1
elif command == 'D':
if cursor_index != len(sentence):
cursor_index += 1
elif command == 'B':
if cursor_index != 0 and len(sentence) != 0:
sentence = sentence[:cursor_index-1] + sentence[cursor_index:]
cursor_index -= 1
else:
if cursor_index == len(sentence):
sentence += command[2:]
elif cursor_index == 0:
sentence = command[2:] + sentence
else:
sentence = sentence[:cursor_index] + command[2:] + sentence[cursor_index:]
cursor_index += len(command[2:])
print(sentence)
◼ 시간초과
◼ 인덱스를 활용한 접근은 실행시간이 오래 걸림
다른 사람이 작성한 코드
import sys
stackLeft = list(sys.stdin.readline().rstrip())
stackRight = list()
n = int(sys.stdin.readline().rstrip())
for i in range(0, n):
command = list(sys.stdin.readline().split())
if command[0] == 'L' and stackLeft:
stackRight.append(stackLeft.pop())
elif command[0] == 'D' and stackRight:
stackLeft.append(stackRight.pop())
elif command[0] == 'B' and stackLeft:
stackLeft.pop()
elif command[0] == 'P':
stackLeft.append(command[1])
print(''.join(stackLeft) + ''.join(list(reversed(stackRight))))
◼ 스택 2개를 활용하여 문제 풀이
pop 연산만으로도 원하는 원소의 삭제가 가능함stackRight는 실제 문자열의 역순으로 원소가 저장되기 때문에 결과를 출력할 때도 역순으로 출력해줘야 한다.