1406. 에디터

곽수경·2023년 10월 26일

1406. 에디터

문제

  • L : 커서를 왼쪽으로 한 칸 옮김 (커서가 문장의 맨 앞이면 무시됨)
  • D : 커서를 오른쪽으로 한 칸 옮김 (커서가 문장의 맨 뒤이면 무시됨)
  • B : 커서 왼쪽에 있는 문자를 삭제함 (커서가 문장의 맨 앞이면 무시됨)
    삭제로 인해 커서는 한 칸 왼쪽으로 이동한 것처럼 나타나지만, 실제로 커서의 오른쪽에 있던 문자는 그대로임
  • P $ : $라는 문자를 커서 왼쪽에 추가함

초기에 편집기에 입력되어 있는 문자열이 주어지고, 그 이후 입력한 명령어가 차례로 주어졌을 때, 모든 명령어를 수행하고 난 후 편집기에 입력되어 있는 문자열을 구하는 프로그램을 작성하시오. 단, 명령어가 수행되기 전에 커서는 문장의 맨 뒤에 위치하고 있다고 한다.

입력

첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수를 나타내는 정수 M(1 ≤ M ≤ 500,000)이 주어진다. 셋째 줄부터 M개의 줄에 걸쳐 입력할 명령어가 순서대로 주어진다. 명령어는 위의 네 가지 중 하나의 형태로만 주어진다.

출력

첫째 줄에 모든 명령어를 수행하고 난 후 편집기에 입력되어 있는 문자열을 출력한다.

풀이

첫번째 제출 : 시간 초과

  1. 커서를 pointer 변수(int)로 표현
  2. 문장은 리스트로 표현, 원소를 추가(insert), 삭제(del)함
  3. 메서드의 시간 복잡도
    • insert : O(n)
    • del : O(n)
      -> 리스트로 편집하는 게 오래걸리는 것 같아서 문자열로 편집 시도
import sys

inputs = list(sys.stdin.readline().strip())
commands = list(map(lambda x : x[:-1], sys.stdin.readlines()[1:]))

class Editor:
    def __init__(self, line):
        self.pointer = len(line);
        self.line = line;
    
    def L(self):
        if self.pointer > 0:
            self.pointer -= 1
            
    def D(self):
        if self.pointer < len(self.line):
            self.pointer += 1;
            
    def B(self):
        if self.pointer > 0:
            del self.line[self.pointer-1];
            self.pointer -= 1;
        
    def P(self, x):
        self.line.insert(self.pointer, x);
        self.pointer += 1;
        
e = Editor(inputs);

for command in commands:
    command = command.split()
    if (command[0] == "L"): e.L()
    elif (command[0] == "D"): e.D()
    elif (command[0] == "B"): e.B()
    else: e.P(command[1]);

print(''.join(e.line))
        

두번째 제출 : 시간 초과

  1. 커서를 pointer 변수(int)로 표현
  2. 문장은 문자열로 표현 / 원소를 추가, 삭제할 때 문자열을 잘랐다가(slicing) 사이에 넣거나 삭제한 후 붙이기(join)로 구현
  3. 메서드의 시간복잡도
    - slice : O(b-a), 처음부터 끝까지 편집하기 때문에 결국 O(n)
    - join : O(n)
    - string + string : O(n^2) - 파이썬은 문자열 내용을 변경할 수 없기 때문에 문자열을 새로운 메모리에 복사하여 새 문자열을 만듦 그래서 오래 걸림
    -> 시간 복잡도 거의 똑같음
import sys

inputs = sys.stdin.readline().strip()
commands = list(map(lambda x : x[:-1], sys.stdin.readlines()[1:]))

class Editor:
    def __init__(self, line):
        self.pointer = len(line);
        self.line = line;
    
    def L(self):
        if self.pointer > 0:
            self.pointer -= 1
            
    def D(self):
        if self.pointer < len(self.line):
            self.pointer += 1;
            
    def B(self):
        if self.pointer > 0:
            frontLine = self.line[:self.pointer-1]
            rearLine = self.line[self.pointer:]
            newLine = frontLine + rearLine
            self.line = newLine
            self.pointer -= 1;
        
    def P(self, x):
        frontLine = self.line[:self.pointer] + x
        rearLine = self.line[self.pointer:]
        newLine = frontLine + rearLine
        self.line = newLine
        self.pointer += 1;
        
e = Editor(inputs);

for command in commands:
    command = command.split()
    if (command[0] == "L"): e.L()
    elif (command[0] == "D"): e.D()
    elif (command[0] == "B"): e.B()
    else: e.P(command[1]);

print(e.line)

세번째 제출 : 정답

  1. 풀이를 찾아보고 스택을 이용한 풀이를 가져옴
  2. 왼쪽에 스택 하나, 오른쪽에 스택 하나(거꾸로된)를 만들고 커서가 이동할 때마다 원소들을 옮김
  3. 오른쪽, 왼쪽 원소들을 활용해서 커서를 표현
  4. 메서드의 시간 복잡도
    • append + pop : O(1)
    • del[-1] : O(1)
      -> 양쪽에 스택을 활용하니 연산들이 O(n)에서 O(1)로 줄어듬
import sys

inputs = list(sys.stdin.readline().strip())
commands = list(map(lambda x : x[:-1], sys.stdin.readlines()[1:]))

class Editor:
    def __init__(self, line):
        self.frontStack = line 
        self.rearStack = []
    
    def L(self):
        if len(self.frontStack) > 0:
            self.rearStack.append(self.frontStack.pop());

    def D(self):
        if len(self.rearStack) > 0:
            self.frontStack.append(self.rearStack.pop());

    def B(self):
        if len(self.frontStack) > 0:
            del self.frontStack[-1]

    def P(self, x):
        self.frontStack.append(x);

e = Editor(inputs);

for command in commands:
    command = command.split()
    if (command[0] == "L"): e.L()
    elif (command[0] == "D"): e.D()
    elif (command[0] == "B"): e.B()
    else: e.P(command[1]);

print(''.join(e.frontStack+e.rearStack[::-1]))
profile
공부 기록

0개의 댓글