直接把求next数组跟标记平移放到一起
#include <iostream> #include <vector> #include <stdlib.h> using namespace std; bool kmp( vector<char>& str1, vector<char>& str2 ) { vector<int> next(str2.size()); int i = 1; int k = 0; while ( i < str2.size() ) { if ( str2[i] == str2[k] ) { next[i] = next[i-1]+1; i++; k++; } else { k = next[i++]; // write like "k = 0; i++;" is easier to understand } } for (int j = 0; j < next.size() ; ++j) { cout << next[j] << " " ; } int begin = 0; while ( begin + str2.size() <= str1.size() ) { int same = 0; while ( str1[begin+same] == str2[same] ) { same++; if ( same == str2.size() ) { return true; } } if ( same == 0 ) begin++; else { begin += same - next[same - 1]; } } return false; } int main() { char a[8] = { 'a','b', 'a','b','a', 'b','c','a'}; char b[16] ="bacbabababcabab"; vector<char> str1(b,b+16); vector<char> str2(a,a+8); bool result = kmp(str1,str2); cout << result << endl; }