1、求两个串的公共“因子串”个数。。。
2、首先用kmp求出每个串的周期,然后枚举较短的串的周期,每次增加一倍(i=k*period1(k>=1)),看是否满足:
1、i是s1.length()的因子。
2、i是s2.length()的因子。
3、period2是i的因子。
如果同时满足这三个条件,则cnt++。
3、注意aba这个字串,它不是一个周期串,而且比较短,如果直接用s1.length()-next[s1.length()]会出错。
4、还有当s1不是周期串时,需要考虑s1不是s2的“因子串”的情况。。。
5、终于理解了失配函数,所谓失配函数值也就是最大的k,使s[0...k-1]=s[i-k+1...i]。(结合有限状态自动机来理解)
6、周期串求法的证明见http://shoutmon.com/?p=330
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<string>
using namespace std;
int next[100010];
string s1,s2;
int cal_period(string s){
next[0]=next[1]=0;
for(int i=1;i<s.length();i++){
int j=next[i];
while(j&&s[j]!=s[i]) j=next[j];
next[i+1]=s[j]==s[i]?j+1:0;
}
return s.length()-next[s.length()];
}
int main(){
cin>>s1>>s2;
int period1=cal_period(s1);
int period2=cal_period(s2);
if(period1>s1.length()/2||period2>s2.length()/2){
if(s1.length()>s2.length()){
swap(s1,s2);
swap(period1,period2);
}
if(s1==s2.substr(0,period2)&&s2.length()%s1.length()==0){
printf("1\n");
return 0;
}else{
printf("0\n");
return 0;
}
}
if(s1.substr(0,period1)!=s2.substr(0,period2)){
printf("0\n");
return 0;
}
if(s1.length()>s2.length()){
swap(s1,s2);
swap(period1,period2);
}
int cnt=0;
for(int i=period1;i<=s1.length();i+=period1){
if(s1.length()%i==0&&s2.length()%i==0&&i%period2==0)
cnt++;
}
printf("%d\n",cnt);
return 0;
}