Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- const int maxn = 1e5 + 10;
- int lps[maxn];
- void preprocess_lps(string pattern) {
- int j = 0, i = 1;
- lps[0] = 0;
- while(i < (int) pattern.size()) {
- if(pattern[i] == pattern[j]) {
- lps[i] = j + 1;
- j++;
- i++;
- }
- else {
- if(j != 0) {
- j = lps[j - 1];
- }
- else {
- lps[i] = 0;
- i++;
- }
- }
- }
- }
- void kmp(string text, string pattern) {
- int n = (int) text.size();
- int m = (int) pattern.size();
- preprocess_lps(pattern);
- int cnt = 0;
- vector<int> idx;
- int i = 0, j = 0;
- while(n - i >= m - j) {
- if(text[i] == pattern[j]) {
- i++;
- j++;
- }
- if(j == m) {
- cnt++;
- idx.push_back(i - j);
- j = lps[j - 1];
- }
- else if(i < n and text[i] != pattern[j]) {
- if(j != 0) {
- j = lps[j - 1];
- }
- else {
- i++;
- }
- }
- }
- if(cnt == 0) {
- cout << "Not Found" << endl;
- return;
- }
- cout << cnt << endl;
- for(int x : idx) {
- cout << x + 1 << " ";
- }
- cout << endl;
- }
- int main() {
- ios_base::sync_with_stdio(false);
- int t;
- cin >> t;
- while(t--) {
- string text, pattern;
- cin >> text >> pattern;
- kmp(text, pattern);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement