码迷,mamicode.com
首页 > 其他好文 > 详细

KMP - 简单应用

时间:2014-08-14 16:37:38      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   div   amp   log   

#include<stdio.h>
#include<string.h>
char s1[1000005],s2[1000005];
int next[1000005];
void get_next(char s[1000005])
{
    int i  = 0;
    int len = strlen(s);
    next[0] = -1;
    int j = -1;
    while(i < len-1)
    {
        if( j == -1 || s[i] == s[j])
        {
            ++i;
            ++j;
            if( s[i] != s[j])
                next[i] = j;
            else
                next[i] = next[j];
        }
        else
            j = next[j];
    }
}

int kmp(char *s,char *p)
{
    int len1 = strlen(s);
    int len2 = strlen(p);
    int i = 0;
    int j  = 0;
    while( i < len1 && j < len2)
    {
        if( j == -1 || s[i] == p[j])
        {
            ++i;
            ++j;
        }
        else
            j = next[j];
    }
    if( j >= len2)
        return i-len2+1;
    else
        return -1;
}
int main()
{

        while(scanf("%s",s1)!=EOF)
        {
        scanf("%s",s2);
        get_next(s2);
        int wz = kmp(s1,s2);
        printf("%d\n",wz);
        }
        return 0;
}

2.

#include <stdio.h>
#include <string.h>
char s[1000001],p[1000001];
int next[1000001];
void getnext(char *p,int *next)
{
    int j,k;
    next[0] = -1;
    j = 0;
    k = -1;
    while(j<strlen(p) - 1)
    {
        if(k == -1 || p[j] == p[k])  // 匹配情况下,p[j] == p[k]
        {
            j++;
            k++;
            next[j] = k;
        }                            // p[j] !=p[k];
        else
        k = next[k];
    }
}
int KMPmatch(char *s,char *p)
{
    int i,j;
    i = 0;
    j = 0;
    getnext(p,next);
    while(i<strlen(s))
    {
        if(j == -1 || s[i] == p[j])
        {
            i++;
            j++;
        }
        else
        j = next[j];
        if(j == strlen(p))
        return i - strlen(p)+1;
    }
    return -1;
}

int main()
{
    while(scanf("%s%s",s,p)!=EOF)
    {
        printf("%d\n",KMPmatch(s,p));
    }
    return 0;
}

  

KMP - 简单应用,布布扣,bubuko.com

KMP - 简单应用

标签:style   blog   color   io   ar   div   amp   log   

原文地址:http://www.cnblogs.com/yangyongqian/p/3912625.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!