C++算法9:KMP应用求字符串最小周期

1.输入重复序列的字符串,如果周期不存在,输出NO,如果周期存在,输出最小周期。
2.代码:

# include <iostream>
# include <string>

using namespace std;

int MinPeriod(char *p)
{
    int len = (int)strlen(p);
    if (len == 0)
        return -1;
    int *next = new int[len];
    next[0] = -1;
    int k = -1;
    int j = 0;
    while (j < len - 1)
    {
        if ((k == -1) || (p[j + 1] == p[k]))
        {
            ++k;
            ++j;
            next[j] = k;
            //cout << j <<  ':' << next[j] << endl;
        }
        else
            k = next[k];
    }
    int last = next[len - 1];
    delete[] next;
    if (len % (len - last) == 0)
        return len - last;
    return -1;

    return 0;
}

int main()
{
    char str[] = { "abcabcabcabc" };
    int min = MinPeriod(str);
    if (min == -1)
    {
        cout << "NO" << endl;
    }
    else
        cout << "YES! 字符串的最小周期为:" << min << endl;
}

3.结果:

YES! 字符串的最小周期为:3
请按任意键继续. . .
    原文作者:KMP算法
    原文地址: https://blog.csdn.net/xuan_zizizi/article/details/81950637
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞