• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

Woosa

合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

KMP字符串模式匹配算法

原理就不说了,学算法的都知道这基本上是查找一个字符串是否在另一个串中位置比较快的算法。代码如下:
[cpp]  
#include <stdio.h>  
#include <string.h>  
#define MAXSIZE 100  
int next[MAXSIZE];  
int S_lenth,D_lenth;  
char source[MAXSIZE],detination[100];  
void get_next()  
{  
    int i=1,j=0;  
    next[1]=0;  
    while(i<=D_lenth)  
    {  
        if(j==0||(detination[i-1]==detination[j-1]))  
        {  
            ++i;  
            ++j;  
            next[i]=j;  
        }  
        else  
        {  
            j=next[j];  
        }  
    }  
}  
int KMP()  
{  
    int i=0,j=1;  
    while(i<=S_lenth&&j<=D_lenth)  
    {  
        if(j==0||(source[i]==detination[j-1]))  
        {  
            ++i;  
            ++j;  
        }  
        else  
        {  
            j = next[j];  
        }  
    }  
    if(j>D_lenth)  
    {  
        return i-D_lenth;  
    }  
    else  
        return 0;  
}  
int main()  
{  
    int i=0;  
    printf("输入源串!!!\n");  
    scanf("%s",&source);  
    printf("输入模式串!!!\n");  
    scanf("%s",&detination);  
    S_lenth = strlen(source);  
    D_lenth = strlen(detination);  
    get_next();  
    printf("next数组元素为:\n");  
    for(i=1;i<=D_lenth;i++)  
    {  
        printf("%d ",next[i]);  
    }  
    printf("\n模式串开始于源串%d位置处",KMP());  
    return 0;  
}  

posted on 2013-03-15 15:32  Woosa  阅读(123)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3