KMP算法的一种实现

/* **************************
 * 字符串模式匹配
 * KMP 算法实现
 *
 * ***************************/

#include <string.h>
#include <stdio.h>

int KMP(const char *pDest,const char *pPattern);
void GetNextArr(const char *pPattern, int *pNext,int nPatternLen);
/* ***************
 * 测试函数
 * 输入两个参数
 * argv[1]:匹配的目标字符串
 * arg[2]:需要匹配的字符串
 * 
 * ***************/
int main(int argc, char *argv[])
{
    int pos = 0;
    if(argc != 3)
    {
        printf("input error\n");
        return -1;
    }
    pos = KMP(argv[1],argv[2]);
    printf("%d \n",pos);
    return 0;
}
/* ******************************
 * 算法实现,如果匹配成功则返回位置(以1开始),匹配失败则返回-1
 * pDest:匹配的目标字符串
 * pPattern:需要匹配的字符串
 * *******************************/
int KMP(const char *pDest,const char *pPattern)
{
    int nDestPos = 0;
    int nPetternPos = 0;
    int nPatternLen = strlen(pPattern);
    int nDestLen = strlen(pDest);
    /*计算pNext数组*/
    int *pNext = (int *)malloc(nPatternLen*sizeof(int));
    GetNextArr(pPattern,pNext,nPatternLen);
    
    if(nPatternLen > nDestLen)
    {
        return -1;
    }
    while(nDestPos < nDestLen && nPetternPos < nPatternLen)
    {
        if(pDest[nDestPos] == pPattern[nPetternPos])
        {
            nPetternPos++;
            nDestPos++;
            continue;
        }
        if (nPetternPos != 0)
        {
            nPetternPos = pNext[nPetternPos-1];
        }else
        {
            nDestPos++;
        }    
    }
    free(pNext);
    /*判断是否匹配成功,并返回结果*/
    return (nPetternPos == nPatternLen)?(nDestPos - nPatternLen + 1):-1;
}
/*计算pNext数组 */
void GetNextArr(const char *pPattern, int *pNext,int nPatternLen)
{
    int pos = 0;
    int j;
    pNext[0] = pNext[1] = 0;
    
    for(j = 1;j < nPatternLen; j++)
    {
        if(pos !=0 && pPattern[j] != pPattern[pos])
        {
            pos = 0;
        }
        if(pPattern[j] == pPattern[pos])
        {
            pos++;
        }
        pNext[j] = pos;
    }
} 

 

posted @ 2013-04-19 10:08  _ccx  阅读(216)  评论(0编辑  收藏  举报