글 작성자: 망고좋아
반응형

1406, 에디터

📁 문제 출처

 

💡 생각

  • index를 사용해서 커서의 위치를 컨트롤하여 작업을 수행해야겠다는 아이디어를 떠올림
  • 시간 초과가 발생
  • 도저히 생각이 안 나서 스택 2개를 가지고 풀이한 것을 참고.
  • s2은 deque를 사용하여 왼쪽에서 원소를 넣었다 뺄 수 있게 하였다.

 

❌ 틀린 코드

import sys

words = list(sys.stdin.readline().strip())
n = int(sys.stdin.readline())

index = len(words)

for i in range(n):
    order = sys.stdin.readline().strip().split()
    if order[0] == "P":
        words.insert(index , order[1])
        index += 1
    elif order[0] == "L":
        if index == 0:
            continue
        else:
            index -= 1
    elif order[0] == "D":
        if index == len(words)+1:
            continue
        else:
            index += 1
    elif order[0] == "B":
        if index == 0:
            continue
        else:
            words.pop(index-1)
            index -= 1

print(''.join(words))

 

🛠 나의 코드

import sys
from collections import deque

s1 = list(sys.stdin.readline().strip())
n = int(sys.stdin.readline())

s2 = deque()

for i in range(n):
    order = sys.stdin.readline().strip().split()
    if order[0] == "P":
        s1.append(order[1])     
    elif order[0] == "L":
        if len(s1) == 0:
            continue
        else:
            s2.appendleft(s1.pop())   
    elif order[0] == "D":
        if len(s2) == 0:
            continue
        else:
            s1.append(s2.popleft())
    elif order[0] == "B":
        if len(s1) == 0:
            continue
        else:
            s1.pop()

print(''.join(s1) + ''.join(list(s2)))

 

✔️ 배운 점

  • 다른 사람들은 deque를 사용하지 않고 s2에 담고 reverse() 해주고 s1과 extend를 해줘서 풀이했다.
  • 또는, s1+ s2[::-1] 이렇게 출력해 줬다.
  • 위 방법을 사용하면 deque 보다 시간을 단축시킬 수 있다.

 

📌 참고한 코드

반응형