꾸준하게 거북이처럼

백준 1406번 파이썬 본문

Computer Science/자료구조

백준 1406번 파이썬

somm12 2022. 7. 13. 09:41
 

1406번: 에디터

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

www.acmicpc.net

처음에 떠올린 문제풀이 방법은 

list를 이용해서 insert 나 del 함수를 이용하는 것이었다. 하지만 이 문제는 시간제한이 0.3초로 짧았고, 시간 초과가 났다.

아무래도 최대 명령어 개수가 50만이고, insert만한다면? 파이썬 list 에서 insert의 시간 복잡도는 O(N)이므로, 또한 여기서 최대 문자열 길이는 60만이므로, 50만 * 60만 => 3천만 연산 + 다수의 if문  존재..

시간 초과가 나기 쉽다.

이쯤되면 pop이나 append와 같이 O(1)만큼 시간이 걸리는 연산만 사용해서 문제를 풀 수 있지 않을까? 생각할 수 있다.

stack 자료구조를 2 개 사용해서 문제를 풀 수 있다.

stack 2개를 이용한 문제풀이 그림

코드 

import sys
if __name__ == "__main__":
    stackLeft = list(sys.stdin.readline().rstrip())
    stackRight = list()

    m = int(sys.stdin.readline().rstrip())
    for _ in range(m):
        command = list(sys.stdin.readline().rstrip().split())
        if command[0] == "P":
            stackLeft.append(command[1])

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

        elif command[0] == "D" and stackRight:
            stackLeft.append(stackRight.pop())

        elif command[0] == "L" and stackLeft:
            stackRight.append(stackLeft.pop())


    print(''.join(stackLeft) + ''.join(list(reversed(stackRight))))

 

참고자료

 

[python] 백준 1406 런타임 에러, 시간 초과 해결

python 으로 백준 1406번 문제를 풀었으나 런타임 오류가 났다. (list의 insert와 pop기능을 통해 처음에 구현했었다.) 테스트 케이스가 잘 돌아가 오류를 못찾겠던 도중 아래의 글을 발견했다. https://w

developer-doreen.tistory.com

 

Comments