BOJ::1786 찾기

시사점

이해(x)

설계, 손 코딩(x)

복잡도

구현(x)

#include<iostream>
#include<string>
#include<vector>
#define rep(i, a, b) for(int i=(a);i<(b); i++)
#define r_rep(i,a,b) for(int i=(a);i>(b); i--)
const int MAX = 1000000 + 100;
typedef long long ll;
using namespace std;

string A, B;
int pi[MAX];
void getPi() {
	int len = B.size();
	int j = 0;
	rep(i, 1, len) {
		while (j > 0 && B[i] != B[j])
			j = pi[j - 1];
		if (B[i] == B[j])
			pi[i] = ++j;
	}
}
void kmp() {
	int len1 = A.size(), len2 = B.size();
	int j = 0;
    vector<int> ans;
	rep(i, 0, len1) {
		while (j > 0 && A[i] != B[j])
			j = pi[j - 1];
		if (A[i] == B[j]) {
			if (j == len2 - 1) {
				ans.push_back(i-len2+1);
				j = pi[j];
			}
			else
				j++;
		}
	}
    cout <<  ans.size() << '\n';
    rep(i, 0, ans.size()) cout << ans[i] + 1<< '\n';
}
void FindString() {
	rep(i, 0, MAX) pi[i] = 0;

	getPi();
	kmp();
}
int main(){
	getline(cin, A);
	getline(cin, B);
    FindString();
    return 0;
}