SUBSTR - Xâu con

Tác giả: happyboy99x

Ngôn ngữ: C++

#include<cstdio>
#include<cstring>

const int N = 1e6;
char s[N+1], t[N+1];
int next[N];

int main() {
	scanf("%s%s", t, s);
	next[0] = -1;
	for(int i = 1; s[i]; ++i) {
		int j = next[i-1];
		while(j >= 0 && s[j+1] != s[i]) j = next[j];
		if(s[j+1] == s[i]) ++j;
		next[i] = j;
	}
	for(int i = 0, j = -1; t[i]; ++i) {
		while(j >= 0 && t[i] != s[j+1]) j = next[j];
		if(t[i] == s[j+1]) ++j;
		if(s[j+1] == 0) {
			printf("%d ", i - j + 1);
			j = next[j];
		}
	}
	printf("\n");
	return 0;
}

Download