王道数据结构 (6) 简单的模式匹配算法

代码:

#include <stdio.h>  
#include "stdlib.h"
 
//宏定义    
#define TRUE   1    
#define FALSE   0    
#define OK    1    
#define ERROR   0  
 
#define  MAXSTRLEN 100
 
typedef char    SString[MAXSTRLEN + 1];
/************************************************************************/
/* 
 返回子串T在主串S中第pos位置之后的位置,若不存在,返回0
*/
/************************************************************************/
int BFindex(SString S, SString T, int pos)
{
    if (pos <1 ||  pos > S[0] ) exit(ERROR);
    int i = pos, j =1;
    while (i<= S[0] && j <= T[0])
    {
        if (S[i] == T[j])
        {
            ++i; ++j;
        } else {
            i = i- j+ 2;
            j = 1;
        }
    }
    if(j > T[0]) return i - T[0];
    return ERROR;
}
 
 
 
void main(){
    SString S = {13,'a','b','a','b','c','a','b','c','a','c','b','a','b'};
    SString T = {5,'a','b','c','a','c'};
    int pos;
    pos = BFindex( S,  T, 1);
    printf("%d", pos);
}

输出:  6 

越努力越幸运
原文地址:https://www.cnblogs.com/guangzhou11/p/13373206.html