poj_2406_kmp_入門_精華操作_解釋
kmp 得精華就是next陣列;
很多部落格瞎幾把寫,誤人子弟,
1.還是年輕,很多灌水部落格就是這樣出現的吧,我遇見過幾個大佬,他們一般寫部落格要麼只發程式碼,要麼很嚴謹,當然很重要的一點是簡潔,的語言精確的描述,
2,還有就是剛寫部落格的小白,這個…..我也是過來人,感覺這個還是自己申明一下,畢竟不成熟.
3.就是培訓班的老師,這部分我不想多說,要麼很強,想靠演算法培訓快速賺錢,要麼就是水的一比,長篇大論說的不知所云,有技術含量的水這是真的煩;
好來說kmp;
kmp實現原理,我之前轉的
next陣列: 記錄長度為i時子串的字首和字尾最長相同部分
next陣列的實現 ,看程式碼解釋和那個圖片
Power Strings
Given two strings a and b we define a*b to be their concatenation. For example, if a = “abc” and b = “def” then a*b = “abcdef”. If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = “” (the empty string) and a^(n+1) = a*(a^n).
Input
Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.
Output
For each s you should print the largest n such that s = a^n for some string a.
Sample Input
abcd
aaaa
ababab
.
Sample Output
1
4
3
Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceed.
題意:
給你字串找能全有由它的子串構成的子串的最小長度
解
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=1000005;
char s[N];
int next[N];
void getnext()
{
// i 代表當前串的長度,j最長公共部分
int len=strlen(s);
int i=0,j=-1;
next[0]=j;
while(i<len)
{
if(s[i]==s[j]||j==-1)
{
i++;
j++;
next[i]=j;
}
else j=next[j];
//當前綴字尾不同時,從長度為j子串公共部分接著匹配
}
}
int main()
{
while(~scanf("%s",s) && s[0]!='.')
{
getnext();
int len=strlen(s);
if(len%(len-next[len])==0)
cout<<len/(len-next[len])<<endl;
else puts("1");
}
return 0;
}