Oulipo (KMP statistical occurrences, bare title)

Oulipo (KMP Count Occurrences)

topic

Seeking in the pattern string to be matched, the number of occurrences of the string.
Input
The first line is a digital T, indicates the number of test data sets. After the data each have two rows:
a first behavior pattern string, a length of not more than 10,000;
second line to be matched string length is not greater than 1,000,000. (All strings consists of only capital letters)
the Output
data output line of each set.
The Input the Sample
. 4
ABCD
ABCD
the SOS
SOSOSOS
CDCDCDC
the CDC
the KMP
SOEASY
the Sample the Output
. 1
. 3
0
0

Problem solutions and ideas

KMP is directly and asked for the number of occurrences.

Note specific region:

  1. Range next array, that is the end of the cycle place.
  2. String pattern may be a case of.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

char str[1000005];
char pi[10005];
int nex[10005];

int m, n;

void getNext(char *p, int *ne)
{
    ne[0] = -1;
    int i = -1, j = 0;
    while (j < n) //注意循环的范围,之前错在 j<n-1
    {

        if (i == -1 || p[i] == p[j]) 
        {
            if (p[i + 1] == p[j + 1])
                ne[++j] = ne[++i];
            else
                ne[++j] = ++i;
        }
        else
            i = ne[i];
    }
}

int kmpSearch()
{
    int j = 0, k = 0, res = 0; //j p;
    while (k < m && j < n)
    {

        if (j == -1 || str[k] == pi[j])
            k++, j++;
        else
            j = nex[j];

        if (j == n)
        {
            res++;
            j = nex[j];//这里也应当注意。当模式串只有一位且等于
                        //主串某位的时候会死循环不加这行会
        }
    }
    return res;
}

int main()
{

    int T;
    cin >> T;
    while (T--)
    {
        scanf("%s", pi);
        scanf("%s", str);
        n = strlen(pi);
        m = strlen(str);
        getNext(pi, nex);
        cout << kmpSearch() << endl;
    }
}

Guess you like

Origin www.cnblogs.com/tttfu/p/11295468.html