若主串S中存在和串T值相同的子串,返回它在主串S中所有出现的位置|数据结构

C++版本

#include <iostream>
#include <Cstring>
using namespace std;


int main()
{
 void GetNext(string T,int next[]);
 void KMP(string K,string T,int next[]);
 int next[] = {0};

 string S;
 string T;
 cout << "请输入主串:\n";
 cin >> S;
 cout << "请输入子串:\n";
 cin >> T;
 KMP(S,T,next);
 //KMP("kabcabcpldab","ab",next);
 return 0;
}

void GetNext(string T,int next[])
{ 
 int p_len = T.size();
 //i匹配后缀
 int i=0;
 //j匹配前缀
 int j=-1;
 next[i] = j;
 while(i<p_len-1)
 {
  if(j==-1 || T[i]==T[j])
  {
   i++;
   j++;
   next[i]=j;
  }
  else
  {
   j=next[j];
  }
 }
}

void KMP(string K,string T,int next[])
{
 GetNext(T,next);
 int k_len = K.size();
 int t_len = T.size();
 //K是主串
 //T是子串
 int i=0;
 int j=0;
 //s记录匹配成功的个数
 int s=0;
 while(i < k_len)
 {
  if(j==-1 || K[i]==T[j])
  {
   i++;
   j++;
  }
  else
  {
   j = next[j];
  }
  if(j == t_len)  //匹配成功
  {
   cout << "第" << ++s << "对匹配成功!起始位置为" << i-j;
   cout << endl;
   j=0;
  } 
 }
}

C语言版本

坑先放在这
不知道为什么编译不过
学数据结构本来想写一个String(串)的数据结构,呜呜呜太难了
由衷感叹各种库真是对程序员太好了

#include <stdio.h>
#define MAX 100

typedef struct 
{
 int length;
 char ch[MAX];
}SString;

int main()
{
 void GetNext(SString *T,int next[]);
 void KMP(SString *K,SString *T,int next[]);
 void InitString(SString *S,char *s);
 int next[] = {0};
 char *S,*V;
 printf("请输入主串!\n");
 gets(S);
 printf("请输入子串!\n");
 gets(V);
 SString *SS;
 SString *VV;
 InitString(SS,S);
 InitString(VV,V);
 KMP(SS,VV,next);
 return 0;
}


void GetNext(SString *T,int next[])
{ 
 int p_len = T->length;
 //i匹配后缀
 int i=0;
 //j匹配前缀
 int j=-1;
 next[i] = j;
 while(i<p_len-1)
 {
  if(j==-1 || T->ch[i]==T->ch[j])
  {
   i++;
   j++;
   next[i]=j;
  }
  else
  {
   j=next[j];
  }
 }
}

void KMP(SString *K,SString *T,int next[])
{
 GetNext(T,next);
 int k_len = K->length;
 int t_len = T->length;
 //K是主串
 //T是子串
 int i=0;
 int j=0;
 //s记录匹配成功的个数
 int s=0;
 while(i < k_len)
 {
  if(j==-1 || K->ch[i]==T->ch[j])
  {
   i++;
   j++;
  }
  else
  {
   j = next[j];
  }
  if(j == t_len)  //匹配成功
  {
   printf("第%d对匹配成功!起始位置为%d\n",++s,i-j);
   j=0;
  } 
 }
}

void InitString(SString *S,char *s)
{
 int i=0;
 char *temp = s;
 while(*temp)
 {
  i++;
 }
 S->length = i;
 //S->ch = new char[i+1];
 i=0;
 while(*s)
 {
  S->ch[i] = s[i];
 }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值