给定两个由英文字母组成的字符串 String 和 Pattern,要求找到 Pattern 在 String 中第一次出现的位置,并将此位置后的 String 的子串输出。如果找不到,则输出“Not Found”。
本题旨在测试各种不同的匹配算法在各种数据情况下的表现。各组测试数据特点如下:
- 数据0:小规模字符串,测试基本正确性;
- 数据1:随机数据,String 长度为 1,Pattern 长度为 1;
- 数据2:随机数据,String 长度为 1,Pattern 长度为 1;
- 数据3:随机数据,String 长度为 1,Pattern 长度为 1;
- 数据4:随机数据,String 长度为 1,Pattern 长度为 1;
- 数据5:String 长度为 1,Pattern 长度为 1;测试尾字符不匹配的情形;
- 数据6:String 长度为 1,Pattern 长度为 1;测试首字符不匹配的情形。
输入格式:
输入第一行给出 String,为由英文字母组成的、长度不超过 1 的字符串。第二行给出一个正整数 N(≤),为待匹配的模式串的个数。随后 N 行,每行给出一个 Pattern,为由英文字母组成的、长度不超过 1 的字符串。每个字符串都非空,以回车结束。
输出格式:
对每个 Pattern,按照题面要求输出匹配结果。
输入样例:
abcabcabcabcacabxy
3
abcabcacab
cabcabcd
abcabcabcabcacabxyz
输出样例:
abcabcacabxy
Not Found
Not Found
//慕课网一个小伙伴做出来的。
//11.30没时间做了,网上也找不到这道题的答案,是今年刚出来的新内容
//应该就是最后的输出问题
#include <stdio.h>
#include <string.h>
#include <stdlib.h> typedef int Position;
#define NotFound -1 void BuildMatch( char *pattern, int *match )
{
Position i, j;
int m = strlen(pattern);
match[] = -; for ( j=; j<m; j++ ) {
i = match[j-];
while ( (i>=) && (pattern[i+]!=pattern[j]) )
i = match[i];
if ( pattern[i+]==pattern[j] )
match[j] = i+;
else match[j] = -;
}
} Position KMP( char *string, char *pattern )
{
int n = strlen(string);
int m = strlen(pattern);
Position s, p, *match; if ( n < m ) return NotFound;
match = (Position *)malloc(sizeof(Position) * m);
BuildMatch(pattern, match);
s = p = ;
while ( s<n && p<m ) {
if ( string[s]==pattern[p] ) {
s++; p++;
}
else if (p>) p = match[p-]+;
else s++;
}
return ( p==m )? (s-m) : NotFound;
}
int main() {
char string[] = {};
char pattern[] = {};
scanf("%s\n", (char *)&string);
int n;
scanf("%d", &n);
for(int i=; i<n; i++) {
scanf("%s\n", (char *)&pattern);
Position p = KMP(string, pattern);
if(p != NotFound) {
if(i == n - ) {
printf("%s", (char *)string+p);
} else {
printf("%s\n", (char *)string+p);
}
} else {
if(i == n - ) {
printf("Not Found");
} else {
printf("Not Found\n");
}
}
}
return ;
}