C++版的KMP算法:
#include <iostream> #include <string> using namespace std; void getNext(int* next, const string& s) { int j = 0; next[0] = 0; for(int i = 1; i < s.size(); i++) { while (j > 0 && s[i] != s[j]) { j = next[j - 1]; } if (s[i] == s[j]) { j++; } next[i] = j; } } void pan(string A, string B) { int next[A.size()]; getNext(next, B); int j = 0; for(int i = 0; i < A.size(); i++) { while(j > 0 && A[i] != B[j]) { j = next[j-1]; } if(A[i] == B[j]) { j++; } if(j == B.size()) { cout << 1; return; } } cout << 0; return; } int main() { string A, B; cin >> A; cin >> B; if(A.size() < B.size()) { pan(B, A); } else pan(A, B); return 0; }