void getNext(string needle, int *next) { int l = needle.length(), i, k; next[0] = -1; k = -1; for(i = 0; i < l-1;) { if(-1 == k || needle[i] == needle[k]) next[++i] = ++k; else k = next[k]; } } int KMP(string s1, string s2, int *next) { int l1 = s1.length(), l2 = s2.length(), i, j; for(i = 0, j = 0; i < l1;) { if(-1 == j || s1[i] == s2[j]) { i++; j++; } else j = next[j]; if(j == l2) return i-j; //返回子串第一次出现的位置下标 } return -1; }