세상을 더 좋게

[백준] 1406 '에디터' 파이썬(python) 본문

카테고리 없음

[백준] 1406 '에디터' 파이썬(python)

나는SOU 2021. 10. 27. 18:26

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

 

1406번: 에디터

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

www.acmicpc.net

from sys import stdin

stack_l = list(stdin.readline().strip()) //커서를 기준으로 왼쪽 리스트
stack_r = [] //커서를 기준으로 오른쪽 리스트
n = int(input())

for _ in range(n) :
    temp = stdin.readline()
    if temp[0] == 'L' :
        if len(stack_l) == 0 :
            continue
        stack_r.append(stack_l.pop())
    elif temp[0] == 'D' :
        if len(stack_r) == 0 :
            continue
        stack_l.append(stack_r.pop())
    elif temp[0] == 'B' :
        if len(stack_l) == 0 :
            continue
        stack_l.pop()
    elif temp[0] == 'P' :
        stack_l.append(temp[2])

        
stack_r.reverse() //리스트를 그대로 쓰면 거꾸로라서 뒤집는다
stack_l.extend(stack_r) //리스트들 합친다

print("".join(stack_l)) //붙여서 출력

스택을 활용한 사례다.

 

가상의 커서를 기준으로 왼쪽 오른쪽을 하나의 리스트를 만들어 pop과 append를 활용해 해결하는 문제다.