1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include <iostream> #include <string> #include <vector>
using namespace std;
void getNextArray(string &str, vector<int> &next) { if (str.length() == 1) { next.push_back(-1); return; } next.resize(str.length()); next[0] = -1; next[1] = 0; int i = 2; int cn = 0; while (i < next.size()) { if (str[i - 1] == str[cn]) { next[i++] = ++cn; } else if (cn > 0) { cn = next[cn]; } else { next[i++] = 0; } } } int KMP(string &s, string &m) { if (m.length() < 1 || s.length() < m.length()) { return -1; } int i1 = 0; int i2 = 0; vector<int> next; getNextArray(m, next); while (i1 < s.length() && i2 < m.length()) { if (s[i1] == m[i2]) { i1++; i2++; } else if (next[i2] == -1) { i1++; } else { i2 = next[i2]; } } return i2 == m.length() ? i1 - i2 : -1; }
void test1() { string s = "abbztabbxabbg"; string m = "abbg"; cout << KMP(s, m) << endl; }
int main() { test1(); return 0; }
|