Find the smallest period of input string in O(n)?

后端 未结 5 452
渐次进展
渐次进展 2020-12-29 15:24

Given the following problem :

Definition :

Let S be a string over alphabet Σ .S\' is the smallest period of S

5条回答
  •  礼貌的吻别
    2020-12-29 16:11

    This problem can easily be solved by KMP

    • Concatenate the string to itself and run KMP on it.
    • Let n be the length of the original string.
    • Search for the first value >= n in the KMP array. That value must be at a position k >= n (0-based).
    • Then k - n + 1 is the length of the shortest period of the string.

    Example:

    Original string = abaaba
    n = 6
    New string = abaabaabaaba
    KMP values for this new string: 0 0 1 1 2 3 4 5 6 7 8 9
    

    The first value >= n is 6 which is at position 8. 8 - 6 + 1 = 3 is the length of the shortest period of the string (aba).

提交回复
热议问题