aboutsummaryrefslogtreecommitdiff
path: root/max_repeat_substr.py
blob: e3d6b9ea2b21d59c9105c0138e3f65a8e2f70400 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 1668. Maximum Repeating Substring

"""
for a string 'sequence', a string 'word' is 'k'-repeating if 'word'
concatenated 'k' times is a substring of 'sequence'. the 'word's maximum
'k'-repeating value is the highest value 'k' where 'word' is 'k'-repeating in
'sequence'. if 'word' is not a substring of 'sequence', 'word's maximum
'k'-repeating value is 0. given strings 'sequence' and 'word', return the
maximum 'k'-repeating value of 'word' in 'sequence'.
"""


class Solution(object):
    def maxRepeating(self, sequence, word):
        """
        :type sequence: str
        :type word: str
        :rtype: int
        """
        n, m = len(sequence), len(word)
        max_repeat = n
        failure = [0] * (m * max_repeat + 1)
        repeat_words = word * max_repeat + "$"
        ans, j = 0, 0
        for i in range(1, len(repeat_words)):
            while j > 0 and repeat_words[j] != repeat_words[i]:
                j = failure[j - 1]
            j += repeat_words[j] == repeat_words[i]
            failure[i] = j
        j = 0
        for i, c in enumerate(sequence):
            while j > 0 and repeat_words[j] != c:
                j = failure[j - 1]
            j += repeat_words[j] == c
            ans = max(ans, j // m)
        return ans


if __name__ == "__main__":
    obj = Solution()
    print(obj.maxRepeating("ababc", "ab"))  # expect: 2
    print(obj.maxRepeating("ababc", "ba"))  # expect: 1
    print(obj.maxRepeating("ababc", "ac"))  # expect: 0