Gemstone's Devlog

[백준] 1406번: 에디터 본문

Data Structure & Algorithms

[백준] 1406번: 에디터

Gemstone 2021. 8. 17. 13:28

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

 

1406번: 에디터

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

www.acmicpc.net

코드

import sys
from collections import deque
input = sys.stdin.readline

stkLeft = list(input().rstrip())
stkRight = []
n = int(input())

for _ in range(n):
    ch = input()
    if ch[0] == 'L':
        if len(stkLeft) == 0:
            continue
        stkRight.append(stkLeft.pop())
    elif ch[0] == 'D':
        if len(stkRight) == 0:
            continue
        stkLeft.append(stkRight.pop())
    elif ch[0] == 'B':
        if len(stkLeft) == 0:
            continue
        stkLeft.pop()
    elif ch[0] == 'P':
        stkLeft.append(ch[2])

stkLeft.extend(stkRight[::-1])

print("".join(stkLeft))

 

커서를 기준으로 왼쪽 stack과 오른쪽 stack을 만들어준다는 생각만 하면 쉽게 문제를 풀 수 있다.

명령어 stack_l(커서 기준 왼쪽) stack_r(커서 기준 오른쪽)
초기 [a, b, c] []
P x [a, b, c, x] []
L [a, b, c] [x]
P y [a, b, c, y] [x]

이후에 stkLeft과 stkRight의 list를 합쳐주면 되는데 stkLeft뒤에 바로 와야할 문자열이 stkRight끝에 마지막으로 들어가기 때문에 stkRight의 list를 reverse해주고 합치면 결과가 나온다.

 

제출 결과

 

참고 블로그 

https://bladejun.tistory.com/12

 

백준 1406번: 에디터 (python, 파이썬)

문제 한 줄로 된 간단한 에디터를 구현하려고 한다. 이 편집기는 영어 소문자만을 기록할 수 있는 편집기로, 최대 600,000글자까지 입력할 수 있다. 이 편집기에는 '커서'라는 것이 있는데, 커서는

bladejun.tistory.com