HDU 2087 剪花布条 KMP

#include<iostream>
#include<cstring>
using namespace std;

char s[1010];
char p[1010];
int nex[1010];

void getNext()
{
    int len = strlen(p);
    nex[0] = -1;
    int i = 0, j = -1;
    while(i < len)
    {
        if(j == -1 || p[i] == p[j])
        {
            i++;
            j++;
            nex[i] = j;
        }
        else j = nex[j];
    }
}

int KMP()
{
    int res = 0;
    int len_s = strlen(s), len_p = strlen(p);
    int i = 0, j = 0;
    while(i < len_s)
    {
        if(j == -1 || s[i] == p[j])
        {
            if(j == len_p-1)
            {
                i++;
                j = 0;
                res++;
            }
            else
            {
                i++;
                j++;
            }
        }
        else j = nex[j];
    }
    return res;
}

int main()
{
    while(scanf("%s", s))
    {
        if(s[0] == '#') break;
        scanf("%s", p);
        getNext();
        printf("%d\n", KMP());
    }
    return 0;
}
上一篇:ajax +formdata ,后台为PHP 实现上传整个文件夹(只适合谷歌浏览器)带进度条


下一篇:JSON对象转成formData对象,formData对象转成JSON对象