KMP算法,Next跳转表的应用(1)

来源:互联网 发布:软件测试技术考题 编辑:程序博客网 时间:2024/06/07 15:50

题目:
定义一个字符串间的运算符 “*”: a=’abc’; b = “def” -> a*b = “abcdef”;
a^0 = “” (空字符串)
a^(n+1) = a*a^n
现输入一系列的字符串,求对于输入的字符串s,是否存在一个s的子串a,使得 s = a^n; 若存在,求出最小长度的a,以及对应的n的值,此时n应该达到最大值。

分析:
首先,在最不理想的状态下: s = s^1 ,即n的最小值为0;
其次,若存在一个子串 a满足条件: 则有 a+a+a……+a (n 个a) = s
回顾KMP算法中next[]跳转表的含义,此时可以有 next[len(s)] = len(a)*(n-1) (其中len(a)为求字符串a的长度)
此时可以得到n的值为 len/ (len(s) - next(len[s]))
另外,上式必须能够整除,所以我们可以将 条件 len% (len(s) - next(len[s])) == 0 作为判断是否满足条件(1)的判别式!

C++ 代码实现:

#include <iostream>#include <string>using namespace std;#define MAX_LEN  1005   // 假设最长字符串为 1000int next[MAX_LEN];int len;int get_next(string &p){    next[0] = -1;    int i = 0;    int j = -1;    while(i<=len) // len 为字符串的长度    {        while( j ==-1 || (i<len && p[i]== p[j]))        {            //cout<<j;            i++;            j++;            next[i] = j;        }        j= next[j];    }    return 0;}int main(){    string str;    while( cin>>str )    {        len = str.length();        get_next(str);        if( (len%(len-next[len]) == 0))            cout<< len/(len-next[len])<<endl;        else            cout<< 1;    }    return 0;}

注:翻译转载!
2016-5-24
TJU-26E

0 0
原创粉丝点击