목차

반복 패턴

ps
링크acmicpc.net/…
출처BOJ
문제 번호16229
문제명반복 패턴
레벨플래티넘 4
분류

문자열

시간복잡도O(n)
인풋사이즈n<=100,000
사용한 언어Python 3.11
제출기록40660KB / 172ms
최고기록120ms
해결날짜2022/12/16

풀이

코드

코드 1 - fail 함수 사용

"""Solution code for "BOJ 16229. 반복 패턴".

- Problem link: https://www.acmicpc.net/problem/16229
- Solution link: http://www.teferi.net/ps/problems/boj/16229

Tags: [KMP algorithm]
"""

from teflib import string as tstring


def main():
    N, K = [int(x) for x in input().split()]
    S = input()

    if K >= N:
        print(N)
        return

    fail = tstring.failure_table(S)
    answer = 0
    border_len = fail[-1]
    while border_len:
        if -N % (N - border_len) <= K:
            answer = N - border_len
        border_len = fail[border_len - 1]
    print(answer)


if __name__ == '__main__':
    main()

코드 2 - z 배열 사용

"""Solution code for "BOJ 16229. 반복 패턴".

- Problem link: https://www.acmicpc.net/problem/16229
- Solution link: http://www.teferi.net/ps/problems/boj/16229

Tags: [Z algorithm]
"""


from teflib import string as tstring


def main():
    N, K = [int(x) for x in input().split()]
    S = input()

    if K >= N:
        print(N)
        return

    z = tstring.z_array(S)
    z[0] = 0
    for i, z_i in enumerate(reversed(z), start=1):
        if i == z_i and -N % (N - i) <= K:
            print(N - i)
            break
    else:
        print('0')


if __name__ == '__main__':
    main()