[백준] 1406번(에디터)

·2023년 5월 1일

백준 문제풀이

목록 보기
57/159

백준 1406번


처음 제출한 코드

import sys

input = sys.stdin.readline

sentence = input().rstrip()
cursor_index = len(sentence)

n = int(input().rstrip())

for i in range(n):
  command = input().rstrip()

  if command == 'L':
    if cursor_index != 0:
      cursor_index -= 1

  elif command == 'D':
    if cursor_index != len(sentence):
      cursor_index += 1

  elif command == 'B':
    if cursor_index != 0 and len(sentence) != 0:
      sentence = sentence[:cursor_index-1] + sentence[cursor_index:]
      cursor_index -= 1

    
  else:
    if cursor_index == len(sentence):
      sentence += command[2:]
    elif cursor_index == 0:
      sentence = command[2:] + sentence
    else:
      sentence = sentence[:cursor_index] + command[2:] + sentence[cursor_index:]
    cursor_index += len(command[2:])

print(sentence)

시간초과
◼ 인덱스를 활용한 접근은 실행시간이 오래 걸림


다른 사람이 작성한 코드

import sys

stackLeft = list(sys.stdin.readline().rstrip())
stackRight = list()

n = int(sys.stdin.readline().rstrip())
for i in range(0, n):
    command = list(sys.stdin.readline().split())
    if command[0] == 'L' and stackLeft:
        stackRight.append(stackLeft.pop())
    elif command[0] == 'D' and stackRight:
        stackLeft.append(stackRight.pop())
    elif command[0] == 'B' and stackLeft:
        stackLeft.pop()
    elif command[0] == 'P':
        stackLeft.append(command[1])

print(''.join(stackLeft) + ''.join(list(reversed(stackRight))))

출처

◼ 스택 2개를 활용하여 문제 풀이

  • 커서를 기준으로 왼쪽 문자열과 오른쪽 문자열을 나눔
  • 커서의 위치를 기준으로 삽입과 삭제가 일어남으로 인덱스 없이 pop 연산만으로도 원하는 원소의 삭제가 가능함
  • stackRight는 실제 문자열의 역순으로 원소가 저장되기 때문에 결과를 출력할 때도 역순으로 출력해줘야 한다.
profile
백엔드 개발자가 되고 싶어요(22.8.15~)

0개의 댓글