- 이전 포스팅에 있었던 [[백준] 1406번 에디터 ★]와 동일한 유형의 연결 리스트 문제였다. 커서 기준 왼쪽 스택과 커서 기준 오른쪽 스택 두 개의 스택을 만들어서 코드를 작성했다.
import sys
input = sys.stdin.readline
T = int(input().strip())
for _ in range(T):
cursor_left_stack = []
cursor_right_stack = []
password = list(input().strip())
for i in range(len(password)):
if password[i] == "<":
if cursor_left_stack:
cursor_right_stack.append(cursor_left_stack.pop())
elif password[i] == ">":
if cursor_right_stack:
cursor_left_stack.append(cursor_right_stack.pop())
elif password[i] == "-":
if cursor_left_stack:
cursor_left_stack.pop()
else:
cursor_left_stack.append(password[i])
cursor_right_stack = reversed(cursor_right_stack)
cursor_left_stack.extend(cursor_right_stack)
print(''.join(cursor_left_stack))
입력
1
<BP<A>>Cd-
출력
BAPC
| 명령어 | 커서 기준 왼쪽 스택 | 커서 기준 오른쪽 스택 |
|---|---|---|
| < | x | x |
| < | x | x |
| B | B | x |
| P | BP | x |
| < | B | P |
| A | BA | P |
| > | B | PA |
| > | x | PAB |
| C | C | PAB |
| d | Cd | PAB |
| - | C | PAB |
extend처리해줘서 join()하면 된다.