파이썬 알고리즘 146번 | [백준 1406번] 에디터 - 스택

Yunny.Log ·2022년 5월 10일
0

Algorithm

목록 보기
149/318
post-thumbnail

146. 에디터

1) 어떤 전략(알고리즘)으로 해결?

  • 처음엔 단순 리스트 비교인줄 알았는데, 스택으로 구현하는 문제
  • 생각보다 스택으로 활용해야만 풀리는 문제들이 한가득이다.
  • 시간 효율적 면에서 훨씬 빠르기에 그런가보다.
  • 스택 활용을 자유자재로 할 수 있도록 열심히 연습해나가자.

2) 코딩 설명

https://kbwplace.tistory.com/87
분의 설명을 보고 이해

왼쪽을 담당하는 스택1
오른쪽을 담당하는 스택2 를 만들어서

<내 풀이>

  • 커서를 기준으로 왼쪽, 오른쪽에 두는 것이 바뀐다고 생각하면 된다.

import sys

stack_left = list(sys.stdin.readline().rstrip())
stack_right = []
N = len(stack_left)
M = int(input())

for _ in range(M):

    command = sys.stdin.readline().split()
    if command[0] == "L" and stack_left:
        stack_right.append(stack_left.pop())
        

    elif command[0] == "D" and stack_right:
       stack_left.append(stack_right.pop())

    elif command[0] == "B" and stack_left:
       stack_left.pop()

    elif command[0] == "P":
       stack_left.append(command[1])


print("".join(stack_left + list(reversed(stack_right))))

p는 커서

<처음 내 틀린 풀이, 문제점>

  • 시간 초과 풀이
import sys

strr=list(input())
n=int(sys.stdin.readline())

cursor = len(strr)-1
totallen = n

for i in range(n):

    inp=list(str(sys.stdin.readline().strip().split()))

    if inp[2]=="D" and cursor<totallen:
        cursor+=1

    elif inp[2] =="B"  and cursor>1:
        totallen-=1
        strr.pop(cursor)
        cursor-=1

    elif inp[2] =="L" and cursor>0:
        cursor-=1

    elif inp[2] =="P":
        letter=inp[7]
        strr.insert(cursor,letter)
    

print("".join(strr))

<반성 점>

<배운 점>

  • pop 이랑 append는 시간 복잡도가 1로 매우 낮으니 얘네만 사용하는 것을 지향하자
  • pop을 하려면 해당 리스트가 존재하는지 체크를 진행하면 된다.

0개의 댓글