串的操作(课堂笔记)

一、串的存储方式

  1.顺序存储方式

#define MAXLEN 100
typedef struct 
{
    char str[MAXLEN];
    int curlen; /* data */
}string;//顺序存储结构

  2.链式存储结构(块链)

typedef NODELEN 100
typedef struct node
{
    char ch;//链式存储结构
    char ch[NODELEN];//块链
    struct node *next;
} node, *pointer;
typedef struct 
{
    pointer head, tail;
    int length;
}linkedstring;

二、串的模式匹配算法

  1.朴素的模式匹配算法

//串的朴素匹配算法
int Index(String S,String T,int pos)
{
    int i = pos;
    int 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];
    }
    else
    {
        return 0;
    }
}

  2.KMP模式匹配算法(未修正+已修正)

//KMP算法
void get_next(String T,int *next)//算出模式串T的next数组
{
    int i, j;
    i = 1;
    j = 0;
    next[1] = 0;
    while(i<T[0])//长度
    {
       if(j==0||T[i]==T[j])
       {
           i++;
           j++;
           next[i] = j;
       }
       else
       {
           j = next[j];
       }
    }
}

void get_nextval(String T,int *nextval)//算出模式串T的改进后的next数组
{
    int i, j;
    i = 1;
    j = 0;
    next[1] = 0;
    while(i<T[0])//长度
    {
       if(j==0||T[i]==T[j])
       {
           i++;
           j++;
           if(T[i]!=T[j])//修改部分
               nextval[i] = j;
           else
           {
               nextval[i] = nextval[j];
           }
           
       }
       else
       {
           j = next[j];
       }
    }
}
int Index_KMP(string S,Sting T,int pos)
{
    int i = pos;
    int j = 1;
    int next[255];
    get_next(T,next);
    get_next_val(T,next);//修正后的next数组
    while(i<=S[0]&&j<=T[0])
    {
        if(j==0||S[i]==T[j])
        {
            i++;
            j++;
        }
        else
        {
            j=next[j];
        }
    }
    if(j>T[0])
        return i-T[0];
    else
        return 0;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值