문제풀이/기타

@[파이썬] [문자열] 백준 20437 문자열 게임 2

승무_ 2023. 1. 6. 11:56

문제

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

 

20437번: 문자열 게임 2

첫 번째 문자열에서 3번에서 구한 문자열은 aqua, 4번에서 구한 문자열은 raquator이다. 두 번째 문자열에서는 어떤 문자가 5개 포함된 문자열을 찾을 수 없으므로 -1을 출력한다.

www.acmicpc.net

코드

from collections import defaultdict

t = int(input())

for _ in range(t):
    st = input()
    n = int(input())
    dict = defaultdict(list)

    for index, value in enumerate(st):
        dict[value].append(index)

    result3 = 10001
    result4 = -1

    for i in dict:
        if len(dict[i]) >= n:
            for j in range(len(dict[i])):
                if j + n <= len(dict[i]):
                    result3 = min(result3, dict[i][n + j - 1] - dict[i][j])
                    result4 = max(result4, dict[i][n + j - 1] - dict[i][j])

    if result3 == 10001 and result4 == -1:
        print(-1)
    else:
        print(result3 + 1, end=" ")
        print(result4 + 1)

생각 정리

문자별 index를 dict에 넣어주고 dict을 sliding window 해주었다.