給定兩個由英文字母組成的字符串 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
//今年又是這樣沒時間來好好看最后的兩道算法題。。 #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[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; }