1406번 : 에디터 - Python

Pobi·2023년 2월 5일
0

PS

목록 보기
40/107

문제

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

풀이

배열을 왼쪽(L) 오른쪽(R)로 나눈 다음에 커서를 기준으로 나눠서 계산 한다. 커서를 왼쪽으로 하나 옮길때는 L에서 pop한다음에 R에 push해준다. 여기서 주의할 것은 R의 경우 뒤에서추가되는 방식이어서 나중에 R을 뒤집어 주어서 출력해줘야 한다.

코드

from sys import stdin

input = stdin.readline

L = list(input().rstrip())
R = list()

for _ in range(int(input())):
    command = list(input().split())
    if command[0] == 'L':
            if L: #L이 비어있다는 것은 가장 왼쪽이라는 소리이기 때문에 왼쪽으로 못가게 해야 한다.
                R.append(L.pop())
    elif command[0] == 'D':
        if R: #R이 비어있다는 것은 가장 오른쪽이라는 소리이기 때문에 오른쪽으로 못가게 해야 한다.
            L.append(R.pop())
    elif command[0] =='B':
        if L:
            L.pop()
    else:
        L.append(command[1])

L.extend(reversed(R)) #reverrse가 아닌 reversed인 이유는 R이 비어 있을때 오류가 나지 않기 위해서이다.
print(''.join(L))

처음 풀이

python의 insert와 pop(숫자)를 이용하여 풀어본다.

처음 코드

from sys import stdin,stdout

input = stdin.readline
print = stdout.write

array = list(input().strip())
point = len(array)

n = int(input())

for i in range(n):
    S = input()
    if 'P' in S:
        a, s = S.split()
        array.insert(point,s)
        point+=1
    elif 'L' in S:
        if point != 0:
            point -=1
    elif 'D' in S:
        if point != len(array):
            point +=1
    elif 'B' in S: 
        if point != 0:
            array.pop(point)
            point -=1
    
print("".join(map(str,array)))

틀린 이유

매 입력마다 insert와 pop을 수행할때마다 배열을 계속 탐색하는데 시간을 많이 써서 시간초과가 난다.

profile
꿈 많은 개발자

0개의 댓글