串的模式匹配

在串的各种操作中。串的模式匹配是经经常使用到的一个算法。串的模式匹配也称为子串的定位操作,即查找子串在主串中出现的位置。

1.经典的模式匹配算法Brute-Force。

2.KMP算法。

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
  
#define MAXSIZE 60  
  
typedef struct  
{  
    char ch[MAXSIZE];  
    int length;  
}SeqString;


#include "SeqString.h"  
/*经典的模式匹配算法Brute-Force*/  
/*假设串採用顺序存储方式存储。则Brute-Force匹配算法例如以下*/  
  
int B_FIndex(SeqString S,int pos,SeqString T)  
/*在主串S中的第pos个位置開始查找子串T,假设找到,返回子串在主串中的位置;否则返回-1*/  
{  
    int i,j;  
    i = pos-1;  
    j = 0;  
    while(i < S.length && j < T.length)  
    {  
        if(S.ch[i] == T.ch[j])  
            /*假设串S和串T中相应的位置的字符相等,则继续比較下一个字符*/  
        {  
            i++;  
            j++;  
        }  
        else  
            /*假设当前相应位置的字符不相等,则从串S的下一个字符開始,从T的第0个字符開始比較*/  
        {  
            i = i-j+1;  
            j = 0;  
        }  
    }  
    if(j >= T.length)  
        /*假设在串S中找到串T,则返回子串T在主串S中的位置*/  
    {  
        return i-j+1;  
    }  
    else  
    {  
        return -1;  
    }  
}  


#include "SeqString.h"  
/*KMP算法*/  
/*KMP算法思想*/  
/*利用模式串T的next函数值求T在主串S中的第pos个字符之间的位置的KMP算法描写叙述例如以下:*/  
  
int KMP_Index(SeqString S,int pos,SeqString T,int next[])  
{  
    int i,j;  
    i = pos-1;  
    j = 0;  
    while(i < S.length && j < T.length)  
    {  
        if(-1 == j || S.ch[i] == T.ch[j])  
            /*假设j=-1或当前字符相等,则继续比較后面的字符*/  
        {  
            i++;  
            j++;  
        }  
        else/*假设当前字符不相等,则将模式串向右移动*/  
        {  
            j = next[j];/*数组next保存next函数值*/  
        }  
    }  
    if(j >= T.length)/*匹配成功。则返回子串T在主串S中的位置。否则返回-1*/  
    {  
        return i-T.length+1;  
    }  
    else  
    {  
        return -1;  
    }  
}  



#include "SeqString.h"  
/*KMP算法*/  
/*求next函数值*/  
/*算法描写叙述例如以下*/  
void GetNext(SeqString T,int next[])  
{  
    int j,k;  
    j = 0;  
    k = -1;  
    next[0] = -1;  
    while(j < T.length)  
    {  
        if(-1 == k || T.ch[j] == T.ch[k])  
        {  
            j++;  
            k++;  
            next[j] = k;  
        }  
        else  
        {  
            k = next[k];  
        }  
    }  
}  



#include "SeqString.h"  
/*KMP算法*/  
/*求next函数值*/  
/*改进算法例如以下*/  
void GetNextVal(SeqString T,int nextval[])  
{  
    int j,k;  
    j = 0;  
    k = -1;  
    nextval[0] = -1;  
    while(j < T.length)  
    {  
        if(-1 == k || T.ch[j] == T.ch[k])  
        {  
            j++;  
            k++;  
            if(T.ch[j] != T.ch[k])  
            {  
                nextval[j] = k;  
            }  
            else  
            {  
                nextval[j] = nextval[k];  
            }  
        }  
        else  
        {  
            k = nextval[k];  
        }  
    }  
}  


posted on 2017-06-29 20:48  wgwyanfs  阅读(357)  评论(0编辑  收藏  举报

导航