1. 程式人生 > >CCF201409-3字符串匹配(KMP)

CCF201409-3字符串匹配(KMP)

主串 not color 利用 出現 算法 cto ret 一行

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 char str[101][101];
 5 char T[101];
 6 void NEXT(const string&T, vector<int>&next){//按模式串生成vector,next(T.size())
 7     next[0] = -1;
 8     for (int i = 1; i<T.size(); i++){
 9         int j = next[i - 1];
10 while (j >= 0 && T[i - 1] != T[j]) j = next[j];//遞推計算 11 if (j >= 0 && T[i - 1] == T[j]) next[i] = j + 1; 12 else next[i] = 0; 13 } 14 } 15 16 char toBig(char a){ 17 if(a>=a&&a<=z){ 18 a+=(A-a); 19 } 20 return a;
21 } 22 int FIND_KMP(const string&S, const string&T,int n){ 23 //利用模式串T的next函數求T在主串S中是否出現的KMP算法 24 //其中T非空, 25 vector<int>next(T.size()); 26 NEXT(T, next); 27 int index, count = 0; 28 for (index = 0; index<S.size(); ++index){ 29 int pos = 0; 30 int iter = index;
31 while (pos<T.size() && iter<S.size()){ 32 if(n==0){//不分大小寫 33 if(toBig(S[iter])== toBig(T[pos])){ ++iter; ++pos; } 34 else{ 35 if (pos == 0) ++iter; 36 else pos = next[pos - 1] + 1; 37 } 38 }else{//區分大小寫 39 if (S[iter] == T[pos]){ ++iter; ++pos; } 40 else{ 41 if (pos == 0) ++iter; 42 else pos = next[pos - 1] + 1; 43 } 44 } 45 } 46 if (pos == T.size() && (iter - index) == T.size())// ++count; 47 { 48 count=1; 49 break; 50 } 51 } 52 return count; 53 } 54 55 int main() 56 { 57 int n,i,m; 58 cin >> T; 59 cin>>n>>m; 60 for(i=0;i<m;i++){ 61 cin>>str[i]; 62 } 63 for(i=0;i<m;i++){ 64 if(FIND_KMP(str[i], T,n)) 65 cout<<str[i]<<endl; 66 } 67 return 0; 68 }
問題描述   給出一個字符串和多行文字,在這些文字中找到字符串出現的那些行。你的程序還需支持大小寫敏感選項:當選項打開時,表示同一個字母的大寫和小寫看作不同的字符;當選項關閉時,表示同一個字母的大寫和小寫看作相同的字符。 輸入格式   輸入的第一行包含一個字符串S,由大小寫英文字母組成。
  第二行包含一個數字,表示大小寫敏感的選項,當數字為0時表示大小寫不敏感,當數字為1時表示大小寫敏感。
  第三行包含一個整數n,表示給出的文字的行數。
  接下來n行,每行包含一個字符串,字符串由大小寫英文字母組成,不含空格和其他字符。 輸出格式   輸出多行,每行包含一個字符串,按出現的順序依次給出那些包含了字符串S的行。 樣例輸入 Hello
1
5
HelloWorld
HiHiHelloHiHi
GrepIsAGreatTool
HELLO
HELLOisNOTHello 樣例輸出 HelloWorld
HiHiHelloHiHi
HELLOisNOTHello 樣例說明   在上面的樣例中,第四個字符串雖然也是Hello,但是大小寫不正確。如果將輸入的第二行改為0,則第四個字符串應該輸出。 評測用例規模與約定   1<=n<=100,每個字符串的長度不超過100。 在KMP原型代碼上做了修改,本題就是對KMP很直接的一個考察。

CCF201409-3字符串匹配(KMP)