1406 (에디터)

Lee Hyun Joon ·2022년 7월 2일

알고리즘정리

목록 보기
1/17

공부 내용 정리

해당 문제를 푸는데 있어 느낀점이 많아서 정리하고자 작성했습니다.

자료구조를 활용하지 못하는 필자의 한계

아래의 코드는 시간초과가 난 코드이기에 그냥 넘어가시는 걸 추천드립니다.

import sys 
from collections import deque
# string_input = [' '] * 600000
string_input = sys.stdin.readline().rstrip('\n')
idx = len(string_input)
total_input = len(string_input)
num = int(input())
def erase(total_input , idx, string_input):
    if idx == 0:
        return total_input, idx, string_input
    else:
        total_input -=1
        front_space = deque(string_input[:idx])
        back_space = deque(string_input[idx:])
        front_space.pop()
        idx -=1 
        front_space += back_space 
        string_input_result = ''.join(front_space)
        return total_input,idx, string_input_result
def add_char(idx, val, string_input, total_input):
    if idx == total_input:
        string_input_result = ''.join([string_input,val])
    else:    
        front_space = deque(string_input[:idx])
        back_space = deque(string_input[idx:])
        front_space.append(val)
        front_space += back_space 
        string_input_result = ''.join(front_space)
        # string_input_result = ''.join([front_space, back_space])

    return string_input_result
for i in range(num):
    try:
        input_option = sys.stdin.readline().rstrip('\n').split(' ')
        option, val = input_option[0], input_option[1]
    except:
        option = input_option[0]
    finally:
        if option == 'B':
            total_input , idx, string_input = erase(total_input , idx, string_input)
            # print(string_input[:10])
        elif option == 'L':
            if idx > 0:
                idx -=1 
        elif option == 'D':
            if idx < total_input:
                idx +=1 
        elif option == 'P':
            string_input = add_char(idx, val, string_input, total_input )
            total_input += 1
            idx +=1

print(''.join(string_input))

위 코드는 두 번째 제출용 코드로 deque를 두 개 사용하여 cursor(idx)를 기준으로 잘라서 삭제, 추가 작업 진행하려고 했습니다. deque를 사용하는 것이 list를 활용하는 것보다 좋다고 판단하여 기대를 했지만, 시간 초과는 여전히 났기에 다른 작성자들의 코드를 참고하여 아래와 같은 코드처럼 표현할 수 있다는 것을 배웠습니다. (어디까지나 참고만 했습니다!)

import sys 
front = list(sys.stdin.readline().rstrip())
back = []

for _ in range(int(sys.stdin.readline())):
    option = list(sys.stdin.readline().split()) # 그냥 공백 split 
    if option[0] == 'L':
        if front:
            back.append(front.pop())
    elif option[0] == 'D':
        if back:
            front.append(back.pop())
    elif option[0] == 'B':
        if front:
            front.pop()
    else:
        front.append(option[1])
front.extend(reversed(back))
print(''.join(front))

위 코드는 두 개의 리스트를 사용하는데, 커서를 따로 체크하지 않고 커서가 항상 front와 back의 중간지점이라고 생각하여 구현했습니다. 커서를 기준으로 왼쪽 값을 삭제하는 과정에서 아래와 같은 방식을 사용합니다.

front.pop() #front 즉, cursor를 기준으로 왼쪽의 list에서 따로 삭제만 해줍니다.

또한 L, D 처럼 커서를 이동하는 것은 값 자체를 front 와 back 사이에 이동하여 표현할 수 있습니다.
이 문제를 통해서 제가 배워갈 수 있는 점이 있어서 남깁니다.

profile
우당탕탕 개발 지망생

0개의 댓글