#include <iostream>
#include <string>
#include <vector>
using namespace std;
string s;
string t;
vector<int> lps(int(1e6+1));
int ans;
void calc(){
int m=s.size(),len=0;
t=s+s;
lps[0]=0;
for(int i=1;i<m;){
if(s[i]==s[len])
lps[i++]=++len;
else
if(len)
len=lps[len-1];
else
lps[i++]=0;
}
}
void kmp(){
calc();
int m=s.size(),n=t.size();
ans=0;
int i=0,j=0;
while(i<n){
if(s[j]==t[i])
i++,j++;
if(j==m)
ans++,j=lps[j-1];
else if(i<n&&s[j]!=t[i])
if(j)
j=lps[j-1];
else
i++;
}
}
int main(){
cin>>s;
while(s!="."){
kmp();
cout<<ans-1<<endl;
cin>>s;
}
}
#include <string>
#include <vector>
using namespace std;
string s;
string t;
vector<int> lps(int(1e6+1));
int ans;
void calc(){
int m=s.size(),len=0;
t=s+s;
lps[0]=0;
for(int i=1;i<m;){
if(s[i]==s[len])
lps[i++]=++len;
else
if(len)
len=lps[len-1];
else
lps[i++]=0;
}
}
void kmp(){
calc();
int m=s.size(),n=t.size();
ans=0;
int i=0,j=0;
while(i<n){
if(s[j]==t[i])
i++,j++;
if(j==m)
ans++,j=lps[j-1];
else if(i<n&&s[j]!=t[i])
if(j)
j=lps[j-1];
else
i++;
}
}
int main(){
cin>>s;
while(s!="."){
kmp();
cout<<ans-1<<endl;
cin>>s;
}
}
Comments
Post a Comment