4、给出一个函数复制两个字符串A和B,A的后几个和B的前几个字节重叠

//利用该进的KMP算法实现复制A和B,A的后几个和B的前几个字节重叠
 //KMP算法
 //求next数组
 void nextCal(const char* str, int * next)
 {
	 int length =strlen(str);
	 int j = 0, k = -1;
	  next[0]= k;
	 while(j < length - 1)
	 {
		 if(k == -1 || str[j] == str[k])
		 {
			 ++k;
			 ++j;
			 next[j] = k;       
/* 
//当str[j] == str[k]时,如果用str[k]比较
//还是不等还要继续找next[k], 不如这里直接给了
			 if(str[j] != str[k])
				 next[j] = k;
			 else
				 next[j] = next[k];
*/
		 }
		 else
			 k = next[k];
	 }
 }
 //KMP算法
 int matchKMP(const char * strD, const char * strP)
 {
	 int length = strlen(strP);
	 int lengthD = strlen(strD);
	 int * next = new int[length];
	 nextCal(strP, next);
	  showArr(next, length);
	 int posD = 0;
	 int posP = 0;
	 while(posD < lengthD && posP < length)
	 {
		 if(posP == -1 || strP[posP] == strD[posD])
		 {
			 posP++;
			 posD++;
		 }
		 else
			 posP = next[posP];
	 }
	 if(posP >= length)
		 return posD - length;
	 else
		 return -1;
 }
 //返回P中和D中重复的字节长度
 int matchStr(const char * strD, const char * strP)
 {
	 int lengthP = strlen(strP);
	 int lengthD = strlen(strD);
	 if(lengthP == 0)
		 return -1;
	 int * next = new int[lengthP];
	 nextCal(strP, next);
	
	 int posD = 0;
	 int posP = 0;
	 while(posD < lengthD)
	 {
		 if(posP == -1 || strP[posP] == strD[posD])
		 {
			 //全部匹配完成,但是posD未到头
			 if(posP >= lengthP - 1)
			 {
				 posP = next[posP];
				 continue;
			 }
			 posP++;
			 posD++;
		
		 }
		 else
			 posP = next[posP];
	 }
	 return posP;
 }
 //复制算法
 char * catStrs(char * strA, char * strB, char *result, int size)
 {
	 int repeatLength = matchStr(strA, strB);
	 int lengthA = strlen(strA);
	
	 strncpy_s(result, size, strA, lengthA - repeatLength);
	result[lengthA - repeatLength] = '\0';

	 strcat_s(result, size, strB);
	 return result;
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值