무제

[백준] 1406번 에디터 본문

Study/Coding Test 오답노트

[백준] 1406번 에디터

mugan1 2024. 11. 9. 16:57

나의 풀이

import sys
input = sys.stdin.readline

word_list = list(input().strip())
n = int(input())
index = len(word_list)

for _ in range(n):
    command = input().split()
    if(command[0] == "P"): 
        word_list.insert(index, command[1]) 
        index += 1
    if(command[0] == "L"):
        if(index !=0) : index -=1
    if(command[0] == "D"):
        if(index !=len(word_list)): index +=1
    if(command[0] == "B"):
        if(index != 0):
            word_list.pop(index-1)
            index -=1
print("".join(word_list))

 

시간초과 발생 ...

insert 자체가 시간복잡도가 O(n)이기 때문에 통과할 수 없었다

 

다른 풀이

import sys
input = sys.stdin.readline

words = list(input().strip())
cursor = []
for _ in range(int(input())):
    command = input().split()
    if(command[0] == "P"): 
        words.append(command[1])
    if(command[0] == "L"):
        if(words): cursor.append(words.pop())
    if(command[0] == "D"):
        if(cursor) : words.append(cursor.pop())
    if(command[0] == "B"):
        if(words): words.pop()
words.extend(reversed(cursor))
print(''.join(words))

 

커서의 위치를 다른 list에 담아주면 된다

이런 깔끔한 방법이 ㅠㅠ

Comments