백준 1406번 에디터


백준 1406번 에디터


내가 푼 답 ⇒ 시간 초과

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import sys
#input = sys.stdin.readline
row = list(input().rstrip())
num = int(input())
p = len(row)
for i in range(num):
req = input().rstrip().split(" ")
if len(req) > 1:
row.insert(p, req[1])
p += 1
else:
req = req[0]
if req == "L":
p = p - 1 if p > 0 else 0
elif req == "D":
p = p + 1 if p < len(row) else p
elif req == "B":
if p > 0:
p = p -1
row.pop(p)

print(''.join(row))

다른방법 고민..

방법 1: 스택 2개를 만들고, 한 쪽의 top이 포인터가 되어 스택끼리 값을 넣었다 뺐다 해준다.
방법 2: collections 의 deque를 사용한다.
방법1 ⇒ 이것도 시간 초과 남 ;;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
stack1 = list(input().rstrip())
stack2 = []
num = int(input())

for i in range(num):
req = input().rstrip().split(" ")
if len(req) > 1:
stack1.append(req[1])
else:
req = req[0]
if req == "L":
if len(stack1) > 0:
stack2.insert(0, stack1.pop())
elif req == "D":
if len(stack2) > 0:
stack1.append(stack2.pop(0))
elif req == "B":
if len(stack1) > 0:
stack1.pop()

stack1.extend(stack2)
print("".join(stack1))

이건 블로그 복붙 방식은 같은데 이건 통과

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from sys import stdin

stk1 = list(stdin.readline().strip())
stk2 = []
n = int(input())
for line in stdin:
if line[0] == 'L':
if stk1: stk2.append(stk1.pop())
else: continue
elif line[0] == 'D':
if stk2: stk1.append(stk2.pop())
else: continue
elif line[0] == 'B':
if stk1: stk1.pop()
else: continue
elif line[0] == 'P':
stk1.append(line[2])
print(''.join(stk1 + list(reversed(stk2))))

이유! insert() 메서드가 시간 초과의 원인이었다. 위 블로그 방식은 그냥 append() 후에 reveresed하는 방식으로 했다.

Comments