void knuth_morris_pratt(string s, string t, vector<int>& pos) {//字符串s在文本t中进行匹配 //返回字符串在文本中匹配到的子串的数量和位置,存储于数组pos中 pos.clear(); int pref[MAX]; //计算字符串s的前缀函数pref compute_prefix(s, pref); int i(0); while(i < (int)t.length()){ int q(0); while(q < (int)s.length() && s[q] == t[i + q]) ++ q; if(q == (int)s.length()) pos.push_back(i); if(q == 0) ++ i; else //移动位移i = q - prefix[q - 1] //这里的q是字符串不匹配的字符下标 i += q - pref[q - 1]; } }
/*KMP:成功返回第一次匹配位置,失败返回-1*/ int kmp(const char *text, const char *pattern) { int i; int j = -1; const int n = strlen(text); const int m = strlen(pattern); if (n == 0 && m == 0)return 0; if (m == 0)return 0; int *next = (int*)malloc(sizeof(int)*m); compute_prefix(pattern, next); for (i = 0; i < n; i++){ while (j>-1 && pattern[j + 1] != text[i]) j = next[j]; if (text[i] == pattern[j + 1])j++; if (j == m - 1){ free(next); return i - j; } } free(next); return -1; }