Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

kmp c++

#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    string l;
    string s;
    cin >> l;
    cin >> s;
    vector<long long>v(s.size(),0);
    int i, j;
    i = 0;
    j = 0;

    for (int i = 0; i < s.size(); i++) {
        i++;
        if (s[j] == s[i]) {
            v[i] = v[i - 1] + 1;
            j++;
        }
        else {
            if (j == 0) {
                j = v[j ];
            }
            else {
                j = v[j - 1];
            }
        }
    }
    j = 0;
    for (int i = 0; i < l.size(); i++) {
        if (l[i] == s[j]) {
            j++;
            if (j = s.size()) {
                cout << "start= " << i - s.size() << " end= " << i ;
                i = l.size();
            }

        }
        else {
            if (j == 0) {
                j = 0;
            }
            else {
                j = v[j - 1];
            }
        }
    }
}
 
PREVIOUS NEXT
Tagged: #kmp
ADD COMMENT
Topic
Name
5+9 =