본문 바로가기
TIL - 프로그래밍/Python 알고리즘

[백준] 9935. 문자열 폭발 - Python

by chaemj97 2022. 9. 23.
728x90

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

 

9935번: 문자열 폭발

첫째 줄에 문자열이 주어진다. 문자열의 길이는 1보다 크거나 같고, 1,000,000보다 작거나 같다. 둘째 줄에 폭발 문자열이 주어진다. 길이는 1보다 크거나 같고, 36보다 작거나 같다. 두 문자열은 모

www.acmicpc.net

 

실패1 - 시간 초과

# 폭발 전 문자열
s = list(input())

# 폭발 문자
explosion = list(input())
e_len = len(explosion)

cnt = -1
# 폭발할게 없을 때까지 == 지난 턴의 폭발 횟수가 0이면 더이상 폭발 할게 없음
while cnt != 0:
    # 이번 턴의 폭발 횟수
    cnt = 0 
    for i in range(0,len(s)-e_len+1):
        # 폭발 문자 확인
        if s[i:i+e_len] == explosion:
            # 폭발
            s = s[:i] + s[i+e_len:]
            cnt += 1

# 폭발 후 남아있는 문자가 있는가?
if s:
    print(''.join(s))
else:
    print('FRULA')

 

실패2 - 시간 초과

# 폭발 전 문자열
s = input()

# 폭발 문자
explosion = list(input())
e_len = len(explosion)

# 결과
result = []

# 한개씩 result에 넣기
# 넣었을때 폭발문자가 완성된다? -> 빼자
for i in s:
    result.append(i)
    if len(result) > e_len and result[-e_len:] == explosion:
        result = result[:-e_len]

# 폭발이 끝난 후 남아있는 문자가 있는가?
if result:
    print(''.join(result))
else:
    print('FRULA')

 

성공

import sys
input = sys.stdin.readline

# 폭발 전 문자열
s = input().strip()
# 폭발 문자
explosion = list(input().strip())
e_len = len(explosion)

# 결과
result = []

# 한개씩 result에 넣기
# 넣었을때 폭발문자가 완성된다? -> pop
for i in s:
    result.append(i)
    if len(result) >= e_len and result[-e_len:] == explosion:
        for _ in range(e_len):
            result.pop()

# 폭발이 끝난 후 남아있는 문자가 있는가?
if result:
    print(''.join(result))
else:
    print('FRULA')

 

  • pop이 오래 걸릴 줄 알고 다른 방법으로 했었는데 pop()이 아니라 pop(0)이 오래 걸리는 거

728x90
반응형

댓글