https://www.acmicpc.net/problem/1406
✅ 문제 조건
명령어와 커서 위치에 따라 문자열 편집
- L : 커서 왼쪽으로 한 칸 옮기기
- D : 커서 오른쪽으로 한 칸 옮기기
- B : 커서 왼쪽에 있는 문자 삭제
- P $ : 커서 왼쪽에 문자 $ 추가
- 모든 명령어는 불가능할 경우 무시
✅ 접근 방식
시간 제한이 0.3초라 무조건 시간초과가 날 거 같았지만 일단 쌩으로 구현해보고 생각해보기로했다.
pop과 insert를 사용해서 먼저 구현하고, 그 후에 rotate를 사용해서 구현했다.
결론은 둘 다 시간초과가 나고, 도저히 생각이 안나서 다른 블로그를 참고했다.
내가 처음에 실패한 코드는 커서를 인덱스 번호로 생각하고 실제로 해당 값을 추가하거나 삭제하는 방식으로 구현했다.
블로그에서 참고한 코드는 커서를 기준으로 두개의 리스트로 구현하고, 그 두 개의 리스트 사이를 커서로 생각하고 pop과 append만 반복하는 방식이었다.
✅ 실패 코드
1. pop, insert 사용
from collections import deque
string = list(input())
N = len(string)
M = int(input())
cursor = len(string)
for _ in range(M):
P, *s = input().split()
if P == 'L'and cursor > 0:
cursor -= 1
elif P == 'D' and cursor < len(string):
cursor += 1
elif P == 'B' and cursor != 0:
string.pop(cursor-1)
cursor -= 1
elif P == 'P':
string.insert(cursor, *s)
cursor += 1
print("".join(string))
2. rotate 사용
from collections import deque
string = deque(input())
N = len(string)
M = int(input())
cursor = len(string)
for _ in range(M):
P, *s = input().split()
if P == 'L' and cursor > 0:
cursor -= 1
elif P == 'D' and cursor < len(string):
cursor += 1
elif P == 'B' and cursor > 0:
string.rotate(-(cursor-1))
string.popleft()
string.rotate(cursor-1)
cursor -= 1
elif P == 'P':
string.rotate(-(cursor))
string.appendleft(s[0])
string.rotate(cursor)
cursor += 1
print("".join(string))
✅ 정답 코드
from collections import deque
string_1 = deque(input())
string_2 = deque([])
M = int(input())
for _ in range(M):
P, *s = input().split()
if P == 'L' and string_1:
char = string_1.pop()
string_2.appendleft(char)
elif P == 'D' and string_2:
char = string_2.popleft()
string_1.append(char)
elif P == 'B' and string_1:
string_1.pop()
elif P == 'P':
string_1.append(*s)
print("".join(string_1), end="")
print("".join(string_2))
이 풀이를 찾고나서 너무 똑똑한 풀이라 꼭 남기고 싶었다~ 왕천재
'algorithm > Structures' 카테고리의 다른 글
[프로그래머스/Lv2] 주식가격 - Python (1) | 2025.03.28 |
---|---|
[Structures] List Comprehension과 any, all (0) | 2025.02.01 |
[백준2405/골드5] 괄호의 값 - Python (0) | 2025.01.31 |
[백준22233/실버3] 가희와 키워드 - Python (0) | 2025.01.28 |