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

문제 풀이(시간초과)
# 시간초과
word = input()
word = list(word)
cursor = len(word)
n = int(input())
for i in range(n):
cmd = input().split()
if cmd[0] == 'L':
if cursor > 0:
cursor -= 1
elif cmd[0] == 'D':
if cursor != len(word):
cursor += 1
elif cmd[0] == 'B':
if cursor != 0:
word.remove(word[cursor-1])
cursor -= 1
elif cmd[0] == 'P':
word.insert(cursor, cmd[1])
cursor += 1
print(''.join(word))
단어와 커서의 위치를 조정하며 풀어보았지만 시간초과가 발생했다.
다른분이 푼 풀이를 보니 커서대신 리스트를 2개로 쪼갠 후 커서를 기준으로 값을 빼고 더한다!
문제풀이(정답)
st1 = list(input().rstrip())
st2 = []
n = int(input())
for i in range(n):
cmd = list(input().split())
if cmd[0] == 'L':
if st1:
st2.append(st1.pop())
if cmd[0] == 'D':
if st2:
st1.append(st2.pop())
if cmd[0] == 'B':
if st1:
st1.pop()
if cmd[0] == 'P':
st1.append(cmd[1])
st1.extend(reversed(st2))
print(''.join(st1))
이런 생각까지는 아직 못하는것같다.. 와우
'알고리즘문제풀이' 카테고리의 다른 글
| [백준/Python] 2161번 카드1 (2) | 2025.03.28 |
|---|---|
| [프로그래머스/Python] 유연근무제 (0) | 2025.03.21 |
| [백준/Python] 9461번 파도반 수열 (0) | 2025.03.14 |
| [백준/Python] 1847번 스택 수열 (0) | 2025.03.12 |
| [백준/Python] 1012번 유기농 배추 (0) | 2025.03.11 |
