#include<iostream>
using namespace std;

void get_next(string T, int* next) {
	next[0] = -1;
	int i = 0;
	int j = -1;

	while (i < T.size() - 1) {
		if (j == -1 || T[i] == T[j]) {
			++i;
			++j;
			next[i] = j;
		}
		else {
			j = next[j];
		}
	}
}

int KMP(string S, string T) {
    int ans = -1;
    int i = 0;
    int j = 0;
    int next[255];
    get_next(T, next);

    while (i < S.size()) {
        if (j == -1 || S[i] == T[j]) {
            ++i;
            ++j;
        }
        else {
            j = next[j];
        }

        if (j == T.size()) {
            ans = i - T.size();
            break;
        }
    }

    return ans;
}

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐