标签:namespace str 字符串 用例 iostream ring 不同 == 输入格式
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 }
标签:namespace str 字符串 用例 iostream ring 不同 == 输入格式
原文地址:http://www.cnblogs.com/gf-fish/p/7779822.html