KMP 串的模式匹配 (25 分)
生活随笔
收集整理的這篇文章主要介紹了
KMP 串的模式匹配 (25 分)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定兩個(gè)由英文字母組成的字符串 String 和 Pattern,要求找到 Pattern 在 String 中第一次出現(xiàn)的位置,并將此位置后的 String 的子串輸出。如果找不到,則輸出“Not Found”。
本題旨在測(cè)試各種不同的匹配算法在各種數(shù)據(jù)情況下的表現(xiàn)。各組測(cè)試數(shù)據(jù)特點(diǎn)如下:
- 數(shù)據(jù)0:小規(guī)模字符串,測(cè)試基本正確性;
- 數(shù)據(jù)1:隨機(jī)數(shù)據(jù),String 長(zhǎng)度為?1,Pattern 長(zhǎng)度為?1;
- 數(shù)據(jù)2:隨機(jī)數(shù)據(jù),String 長(zhǎng)度為?1,Pattern 長(zhǎng)度為?1;
- 數(shù)據(jù)3:隨機(jī)數(shù)據(jù),String 長(zhǎng)度為?1,Pattern 長(zhǎng)度為?1;
- 數(shù)據(jù)4:隨機(jī)數(shù)據(jù),String 長(zhǎng)度為?1,Pattern 長(zhǎng)度為?1;
- 數(shù)據(jù)5:String 長(zhǎng)度為?1,Pattern 長(zhǎng)度為?1;測(cè)試尾字符不匹配的情形;
- 數(shù)據(jù)6:String 長(zhǎng)度為?1,Pattern 長(zhǎng)度為?1;測(cè)試首字符不匹配的情形。
輸入格式:
輸入第一行給出 String,為由英文字母組成的、長(zhǎng)度不超過?1?的字符串。第二行給出一個(gè)正整數(shù)?N(≤),為待匹配的模式串的個(gè)數(shù)。隨后?N?行,每行給出一個(gè) Pattern,為由英文字母組成的、長(zhǎng)度不超過?1?的字符串。每個(gè)字符串都非空,以回車結(jié)束。
輸出格式:
對(duì)每個(gè) Pattern,按照題面要求輸出匹配結(jié)果。
輸入樣例:
abcabcabcabcacabxy 3 abcabcacab cabcabcd abcabcabcabcacabxyz輸出樣例:
abcabcacabxy Not Found Not Found //今年又是這樣沒時(shí)間來好好看最后的兩道算法題。。 #include <stdio.h> #include <string.h> #include <stdlib.h>typedef int Position; #define NotFound -1void BuildMatch( char *pattern, int *match ) {Position i, j;int m = strlen(pattern);match[0] = -1;for ( j=1; j<m; j++ ) {i = match[j-1];while ( (i>=0) && (pattern[i+1]!=pattern[j]) )i = match[i];if ( pattern[i+1]==pattern[j] )match[j] = i+1;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 ( s<n && p<m ) {if ( string[s]==pattern[p] ) {s++; p++;}else if (p>0) p = match[p-1]+1;else s++;}return ( p==m )? (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 i=0; i<n; i++) {scanf("%s\n", (char *)&pattern);Position p = KMP(string, pattern);if(p != NotFound) {if(i == n - 1) {printf("%s", (char *)string+p);} else {printf("%s\n", (char *)string+p);}} else {if(i == n - 1) {printf("Not Found");} else {printf("Not Found\n");}}}return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/wanghao-boke/p/10946367.html
總結(jié)
以上是生活随笔為你收集整理的KMP 串的模式匹配 (25 分)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 欢喜猎人剧情介绍
- 下一篇: Makefile(一)