Chinaunix首页 | 论坛 | 博客
  • 博客访问: 738374
  • 博文数量: 251
  • 博客积分: 10367
  • 博客等级: 上将
  • 技术积分: 2750
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-10 14:43
文章分类

全部博文(251)

文章存档

2009年(2)

2008年(86)

2007年(163)

KMP

分类: C/C++

2008-03-22 09:18:31

/* -*- C -*-
 *
 * KMP.c -
 *
 * Author : heixia
 * Created On : Sat Mar 22 08:54:54 2008
 *
 */


#include <stdio.h>
#include <stdlib.h>

#define MAX 1000

void GetNextval( char *t,int nextval[ ] );
int KMPIndex( char *s,char *t );

int main( ){
     char s[ 50 ] = "abcaabbabcabaacbacba";
     char t[ 10 ] = "abcabaa";
     int next[ 10 ];

     int i = 0;

     i = KMPIndex( s,t );

     if( i != -1 )
          printf("The matched position is: %d\n",i);
     else
          printf( "Can't be matched.\n" );
}

void GetNextval( char *t,int nextval[ ] ){
     int j = 0,k = -1,len = strlen( t );
     nextval[ 0 ] = -1;

     
     while( j < len ){
          if( k == -1 || t[ j ] == t[ k ] ){
               j ++;
               k ++;
               if( t[ j ] != t[ k ] )
                    nextval[ j ] = k;
               else
                    nextval[ j ] = nextval[ k ];
          }
          else
               k = nextval[ k ];
     }
}

int KMPIndex( char *s,char *t ){
     int next[ MAX ],i = 0,j = 0,v;

     int len1 = strlen( s ),len2 = strlen( t );
     
     GetNextval( t,next );

     while( i < len1 && j < len2 ){
          if( j == -1 || s[ i ] == t[ j ] ){
               i ++;
               j ++;
          }
          else
               j = next[ j ];
     }

     if( j >= len2 )
          v = i- len2;
     else
          v = -1;

     return v;
}


讲解可参考:KMP算法详解
阅读(793) | 评论(0) | 转发(0) |
0

上一篇:8数码问题

下一篇:生活的另一面

给主人留下些什么吧!~~