알고리즘/백준(BOJ)

[백준/BOJ]#1406:에디터[스택/파이썬/python]

https://www.acmicpc.net/problem/1406

 

1406번: 에디터

첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수

www.acmicpc.net

처음에 보고 문자열로 파싱하는게 가장 빠르다고 판단해서 풀었는데 시간초과가 떴다. 

시간초과 코드

#1406_에디터
s=str(input())
num=int(input())
cursor=len(s)
for _ in range(num):
    ctrl=list(map(str,input().split()))
    if cursor<0:
        cursor=0

    if ctrl[0]=='P':
        if cursor==0:
            s=ctrl[1]+s
        else:
            s = s[0:cursor]+ctrl[1]+s[cursor:]
        cursor = cursor+1
    elif ctrl[0]=='L':
        if cursor==0:
            continue
        cursor = cursor-1
    elif ctrl[0]=='D':
        if cursor==len(s):
            continue
        cursor = cursor+1
    elif ctrl[0]=='B':
        if cursor==0:
            continue
        s = s[0:cursor-1]+s[cursor:]
        cursor=cursor-1

print(s)

알고보니 스택 문제였다,, 스택이 시간복잡도가 훨씬 빠르다

 

정답코드

#1406_에디터
from sys import stdin
s=list(stdin.readline().strip())
res=[]
num=int(input())
cursor=len(s)
for _ in range(num):
    ctrl=list(map(str,input().split()))

    if ctrl[0]=='P':
        s.append(ctrl[1])
 
    elif ctrl[0]=='L':
        if s:
            res.append(s.pop())        
        else: continue
    elif ctrl[0]=='D':
        if res:
            s.append(res.pop())
        else:continue
    elif ctrl[0]=='B':
        if s:
            s.pop()
        else: continue


print(''.join(s + list(reversed(res))))

스택 두개를 놓고 커서 기준으로 분할되게 서로 넣고 빼면된다.