余姚网站推广公司,广西钦州有做网站的公司吗,厦门定制网站建设,黄石网站建设教程给定两个由英文字母组成的字符串 String 和 Pattern#xff0c;要求找到 Pattern 在 String 中第一次出现的位置#xff0c;并将此位置后的 String 的子串输出。如果找不到#xff0c;则输出“Not Found”。 本题旨在测试各种不同的匹配算法在各种数据情况下的表现。各组测试… 给定两个由英文字母组成的字符串 String 和 Pattern要求找到 Pattern 在 String 中第一次出现的位置并将此位置后的 String 的子串输出。如果找不到则输出“Not Found”。 本题旨在测试各种不同的匹配算法在各种数据情况下的表现。各组测试数据特点如下 数据0小规模字符串测试基本正确性数据1随机数据String 长度为 1Pattern 长度为 1数据2随机数据String 长度为 1Pattern 长度为 1数据3随机数据String 长度为 1Pattern 长度为 1数据4随机数据String 长度为 1Pattern 长度为 1数据5String 长度为 1Pattern 长度为 1测试尾字符不匹配的情形数据6String 长度为 1Pattern 长度为 1测试首字符不匹配的情形。输入格式: 输入第一行给出 String为由英文字母组成的、长度不超过 1 的字符串。第二行给出一个正整数 N≤为待匹配的模式串的个数。随后 N 行每行给出一个 Pattern为由英文字母组成的、长度不超过 1 的字符串。每个字符串都非空以回车结束。 输出格式: 对每个 Pattern按照题面要求输出匹配结果。 输入样例: abcabcabcabcacabxy
3
abcabcacab
cabcabcd
abcabcabcabcacabxyz输出样例: abcabcacabxy
Not Found
Not Found //今年又是这样没时间来好好看最后的两道算法题。。
#include stdio.h
#include string.h
#include stdlib.htypedef int Position;
#define NotFound -1void BuildMatch( char *pattern, int *match )
{Position i, j;int m strlen(pattern);match[0] -1;for ( j1; jm; j ) {i match[j-1];while ( (i0) (pattern[i1]!pattern[j]) )i match[i];if ( pattern[i1]pattern[j] )match[j] i1;else match[j] -1;}
}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 0;while ( sn pm ) {if ( string[s]pattern[p] ) {s; p;}else if (p0) p match[p-1]1;else s;}return ( pm )? (s-m) : NotFound;
}
int main() {char string[1000001] {0};char pattern[1000001] {0};scanf(%s\n, (char *)string);int n;scanf(%d, n);for(int i0; in; i) {scanf(%s\n, (char *)pattern);Position p KMP(string, pattern);if(p ! NotFound) {if(i n - 1) {printf(%s, (char *)stringp);} else {printf(%s\n, (char *)stringp);}} else {if(i n - 1) {printf(Not Found);} else {printf(Not Found\n);}}}return 0;
} 转载于:https://www.cnblogs.com/wanghao-boke/p/10946367.html