http://ac.jobdu.com/problem.php?pid=1149
含有两种解法 : kmp or 暴力
#include <stdio.h>
#include <cstring>
#include <algorithm>
typedef struct item{
char s[102];
int times;
bool friend operator < (struct item a, struct item b){
return strcmp(a.s,b.s) < 0;
}
} Item;
int search(char substr[],char str[]){
int subl = (int) strlen(substr);
int len = (int) strlen(str);
int i,j,k,t = 0;
for ( i = 0; i < len-subl+1; ++i) {
for ( j = 0,k=i; j < subl; ++k, ++j) {
if(str[k] != substr[j]) break;
}
if(j == subl) t++;
}
return t;
}
void getNext(char p[], int next[]){
int j,k;
next[0] = -1;
j = 0;
k = -1;
int plen = (int) strlen(p);
while(j < plen - 1) {
if(k==-1 || p[j] == p[k]){
++j;
++k;
next[j] = k;
}else{
k = next[k];
}
}
}
int KMPmatch(char substr[],char str[]){
int times = 0;
int next[102];
int i,j;
i = 0,j=0;
getNext(substr,next);
int len =(int) strlen(str);
int subl = (int) strlen(substr);
while(i<len){
if(j==-1||str[i] == substr[j]){
i++;
j++;
}else{
j = next[j];
}
if(j == subl ){
times++;
i = i-j+1;
j=0;
}
}
return times;
}
int main(){
char str[102];
char substr[102];
Item items[15000];
int n=0;
while(scanf("%s",str)!=EOF){
n = 0;
int len = (int) strlen(str);
for (int i = 0; i < len; ++i) {
for (int j = i; j <len; j++) {
strncpy(substr,str+i,(unsigned) (j-i+1));
substr[j-i+1] = '\0';
int times = KMPmatch(substr,str);
//int times = search(substr,str);
strcpy(items[n].s,substr);
items[n++].times = times;
}
}
std::sort(items,items+n);
char pre[102]={'\0'};
for (int i = 0; i < n; ++i) {
if(items[i].times > 1 && strcmp(items[i].s,pre)!=0){
printf("%s %d\n",items[i].s,items[i].times);
strcpy(pre,items[i].s);
}
}
}
}