//
// main.c
// test
//
// Created by 胡博豪 on 16/2/29.
// Copyright © 2016年 胡博豪. All rights reserved.
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int *next(const char *string) {
int *next = (int *)malloc(sizeof(int) * 100);
next[0] = next[1] = 0;
int i = 0, j = 1;
while (++j < strlen(string)) {
if (string[i] != string[j]) {
next[j] = 0;
i = 0;
} else {
i++;
next[j] = next[j - 1] + 1;
}
}
return next;
}
int KMP(const char *ms, const char *os, const int *next) {
int i, j = 0;
for (i = 0; i < strlen(ms);) {
if (ms[i] == os[j]) {
j++;
i++;
} else {
if (j == 0) {
i++;
}
j = next[j];
}
if (j == strlen(os)) {
return i - j + 1;
}
}
return -1;
}
int count_str_in_str(char *str_m, const char *str_o) {
int count = 0, temp = 0;
int *n = next(str_o);
char *str_temp = str_m;
while (temp != -1) {
temp = KMP(str_temp, str_o, n);
str_temp += temp + 1;
count++;
}
free(n);
return count - 1;
}
int main(int argc, const char * argv[]) {
int n, index;
while(~scanf("%d", &n)) {
char **sa = (char **)malloc(sizeof(char *) * n);
for (index = 0; index < n; index++) {
char *temp = (char *)malloc(sizeof(char) * 100);
scanf("%s", temp);
sa[index] = temp;
}
char data[100001];
scanf("%s", data);
char *re = NULL;
int amount = 0;
for (index = 0; index < n; index++) {
int te = count_str_in_str(data, sa[index]);
if (te > amount) {
amount = te;
re = sa[index];
}
}
if (amount == 0) {
printf("exciting\n");
} else {
printf("%s %d\n", re, amount);
}
for (index = 0; index < n; index++) {
free(sa[index]);
}
free(sa);
}
return 0;
}
KMP算法(尝试)
最新推荐文章于 2025-04-04 21:54:16 发布