数据结构与算法--字符串(知识点)

文章介绍了KMP算法的get_nextval和Index_KMP函数实现,用于模式串在主串中的匹配,以及BF(BruteForce)算法求解模式串在主串中第一次出现的位置。KMP算法利用next数组优化了匹配过程,而BF算法则采用暴力逐个字符比较。
摘要由CSDN通过智能技术生成

KMP:

函数get_nextval(char T[], int nextval[])是计算字符串T的next数组,函数Index_KMP(char S[], char T[], int pos, int next[])是KMP算法。

函数接口定义:

void get_nextval(char T[], int next[]);
int Index_KMP(char S[], char T[], int pos, int next[]);

其中 T 是模式串,S是主串,next是next数组。

裁判测试程序样例:

 

输入样例:

第一行输入主串,第二行输入模式串:

abdsegdsagddfddfedfgds
egdsa

输出样例:

输出子串在主串中第p个位置后首次出现的位序:

5

#include<cstring>
#include<iostream>
using namespace std;
​
#define MAXSTRLEN 255 
​
void get_nextval(char T[], int next[]);
int Index_KMP(char S[], char T[], int pos, int next[]);
​
int main()
{
char S[MAXSTRLEN+1],T[MAXSTRLEN+1];
char S1[MAXSTRLEN],S2[MAXSTRLEN];
cin >> S1 >> S2;
strcpy(&S[1],S1);
strcpy(&T[1],S2);    
S[0]=strlen(S1);
T[0]=strlen(S2);
int *next = new int[T[0]+1];
get_nextval(T,next);
cout<<Index_KMP(S,T,1,next);
return 0; 
}
​
/* 请在这里填写答案 */
//书P95
void get_nextval(char T[],int next[])
{
    int i=1,j=0;
    while(i<T[0]){//T[0]为字符串的长度
        next[1]=0;
        if(next[i]==next[j]||j==0){
            ++i;
            ++j;
            next[i]=j;
            if(T[i]==T[j])//优化
                next[i]=next[j];
            else
                next[i]=j;
        }
        else
            j=next[j];
    }
}
//书P96
int Index_KMP(char S[],char T[],int pos,int next[])
{
    int i=pos,j=1;
    get_nextval(T,next);
    while(i<=S[0]&&j<=T[0]){//反复比较对应字符来开始匹配
        if(S[i]==T[j]||j==0){
            ++i;
            ++j;
        }
        else
            j=next[j];
    }
    if(j>T[0])
        return i-T[0];
    else
        return 0;
}

模式匹配:

给出主串s和模式串t,其长度均不超过1000。本题要求实现一个函数BF(string s, string t),求出模式串t在主串s中第一次出现的位置(从0开始计算),如果在s中找不到t,则输出-1

函数接口定义:

/* s为主串,t为模式串。
 * 函数返回t在s中第一次出现的位置。
 */
int BF(string s, string t);

其中 st 分别为主串和模式串,长度均不超过1000。函数返回模式串t在主串s中第一次出现的位置(从0开始计算),如果在s中找不到t,则输出-1

裁判测试程序样例:

#include <bits/stdc++.h>
using namespace std;
​
/* s为主串,t为模式串。
 * 函数返回t在s中第一次出现的位置。
 */
int BF(string s, string t);
​
int main(int argc, char const *argv[])
{
    string s, t;
    getline(cin, s);    //输入主串
    getline(cin, t);    //输入模式串
    int pos = BF(s, t);    //搜索
    cout << pos << endl;//输出模式串在主串中第一次出现的位置
    return 0;
}
​
/* 请在这里填写答案 */

输入样例1:

This is a test string
is

输出样例1:

2

输入样例2:

This is a test string
The

输出样例2:

-1

//书P90
int BF(string s,string t)
{
    int i=0,j=0,len1=s.length(),len2=t.length();
    while(i<len1&&j<len2){//反复比较对应字符来开始匹配
        if(s[i]==t[j])
            i++;
            j++;
        else
            i=i-j+1;
            j=0;
    }
    if(j>=len2)
        return i-len2;
    else 
        return -1;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值