728x90
https://www.acmicpc.net/problem/1406
스택 혹은 큐를 활용해서 풀면 되는 문제.
커서를 기준으로 left, right 두 스택 혹은 큐로 나눠서 로직을 구현하면 된다.
처음에는 스택을 활용해서 풀었다.
import sys
input = sys.stdin.readline
left = list(input().rstrip())
right = []
n = int(input()) # 명령 개수
for _ in range(n):
command = input().rstrip()
if command == 'L':
if left:
char = left.pop()
right.append(char)
elif command == 'D':
if right:
char = right.pop()
left.append(char)
elif command == 'B':
if left:
left.pop()
else:
command, char = command.split()
left.append(char)
print("".join(left) + "".join(right[::-1]))
스택이므로 right를 더해줄 때, 순서를 뒤집어서 더해줘야 한다.
큐를 사용하면 그냥 더해주면 된다.
import sys
from collections import deque
input = sys.stdin.readline
# 커서를 기준으로 스택 2개로 분리
left = deque(list(input().rstrip()))
right = deque([])
n = int(input()) # 명령 개수
for _ in range(n):
command = input().rstrip()
# 커서를 왼쪽으로 옮김
# left에서 pop해서 right에 push
if command == 'L':
if left:
char = left.pop()
right.appendleft(char)
# 커서를 오른쪽으로 옮김
# right에서 pop해서 left에 push
elif command == 'D':
if right:
char = right.popleft()
left.append(char)
# 커서 왼쪽에 있는 문자 삭제
# left에서 pop
elif command == 'B':
if left:
left.pop()
# 커서 왼쪽에 문자 추가
# left에 push
else:
command, char = command.split()
left.append(char)
print("".join(left + right))
appendleft, popleft를 잘 활용하면 된다.
아이디어 생각해내는게 중요한 문제
728x90
'알고리즘 > 백준' 카테고리의 다른 글
9935번: 문자열 폭발 (0) | 2024.05.21 |
---|---|
10799번: 쇠막대기 (0) | 2024.05.15 |
1461번: 도서관 (0) | 2024.05.13 |
1689번: 겹치는 선분 (0) | 2024.05.06 |
1946번: 신입 사원 (0) | 2024.05.05 |
728x90
https://www.acmicpc.net/problem/1406
스택 혹은 큐를 활용해서 풀면 되는 문제.
커서를 기준으로 left, right 두 스택 혹은 큐로 나눠서 로직을 구현하면 된다.
처음에는 스택을 활용해서 풀었다.
import sys
input = sys.stdin.readline
left = list(input().rstrip())
right = []
n = int(input()) # 명령 개수
for _ in range(n):
command = input().rstrip()
if command == 'L':
if left:
char = left.pop()
right.append(char)
elif command == 'D':
if right:
char = right.pop()
left.append(char)
elif command == 'B':
if left:
left.pop()
else:
command, char = command.split()
left.append(char)
print("".join(left) + "".join(right[::-1]))
스택이므로 right를 더해줄 때, 순서를 뒤집어서 더해줘야 한다.
큐를 사용하면 그냥 더해주면 된다.
import sys
from collections import deque
input = sys.stdin.readline
# 커서를 기준으로 스택 2개로 분리
left = deque(list(input().rstrip()))
right = deque([])
n = int(input()) # 명령 개수
for _ in range(n):
command = input().rstrip()
# 커서를 왼쪽으로 옮김
# left에서 pop해서 right에 push
if command == 'L':
if left:
char = left.pop()
right.appendleft(char)
# 커서를 오른쪽으로 옮김
# right에서 pop해서 left에 push
elif command == 'D':
if right:
char = right.popleft()
left.append(char)
# 커서 왼쪽에 있는 문자 삭제
# left에서 pop
elif command == 'B':
if left:
left.pop()
# 커서 왼쪽에 문자 추가
# left에 push
else:
command, char = command.split()
left.append(char)
print("".join(left + right))
appendleft, popleft를 잘 활용하면 된다.
아이디어 생각해내는게 중요한 문제
728x90
'알고리즘 > 백준' 카테고리의 다른 글
9935번: 문자열 폭발 (0) | 2024.05.21 |
---|---|
10799번: 쇠막대기 (0) | 2024.05.15 |
1461번: 도서관 (0) | 2024.05.13 |
1689번: 겹치는 선분 (0) | 2024.05.06 |
1946번: 신입 사원 (0) | 2024.05.05 |