diff --git "a/2109020144/chap3/\345\256\236\351\252\2146.cpp" "b/2109020144/chap3/\345\256\236\351\252\2146.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..a86636f589fa185c99e42df299d49de53fd8a6db --- /dev/null +++ "b/2109020144/chap3/\345\256\236\351\252\2146.cpp" @@ -0,0 +1,44 @@ +#include +using namespace std; +int nextarr[100]; + +void getnext(string s) { + int j = 0, k = -1; + nextarr[0] = -1; + while (j < s.length()) { + if (k == -1 || s[j] == s[k]) { + j++; + k++; + nextarr[j] = k; + } + else { + k = nextarr[k]; + } + } +} + +int KMP(string s, string t) { + int i = 0, j = 0; + int cnt = 0; + while (i < s.length()) { + if (j == -1 || s[i] == t[j]) { + i++, j++; + } + else { + j = nextarr[j]; + } + if (j == t.length()) { + cnt++; + j = nextarr[j]; + } + } + return cnt; +} + +int main() { + string s = "aaabbdaabbde"; + string t = "aabbd"; + getnext(t); + cout << KMP(s, t); + return 0; +} \ No newline at end of file