KMP-删除字符串中给定的字符串

#include<iostream>
using namespace std;
#define NSIZ 1000
int Next[NSIZ];
char str1[NSIZ];
char str2[NSIZ];
void getNext(char str[], int n)
{
	if (!str || !n)
	{
		return;
	}
	int i = 0, j = -1;
	Next[i] = -1;
	while(i < n)
	{
		if (-1 == j || str[i] == str[j])
		{
			++i;
			++j;
			Next[i] = j;
		}
		else
		{
			j = Next[j];
		}
	}
}
//最坏的情况O((n/m)*(n+m))
//最好的情况O(2(n+m))
//这里用自身做标记位,若str1[i] = 0,表示第i个字符已经匹配过
//str2[i] != 0,表示第i个字符没有匹配过
//参数str1 表示母串,str2表示删除的子串
//返回值表示删除的子串在母串中的个数
int Kmp(char *str1, char * str2)
{
	if (!str1 || !str2)
	{
		return 0;
	}
	int flag = 1;
	int count = 0;
	int n2 = strlen(str2);
	int n1 = strlen(str1);
	int i = 0, j = 0, k = 0;
	//子串长度为1时
	if (n2 == 1)
	{
		for (i = 0, j = 0;i < n1; ++i)
		{
			if (str1[i] != str2[0])
			{
				str1[j++] = str1[i];
			}
			else
			{
				count++;
			}
		}
		str1[j] = 0;
		return count;
	}
	//若子串长度比母串长度大
	if (n2 > n1)
	{
		return count;
	}
	//子串长度不为1时
	getNext(str2, n2);
	while(flag == 1)
	{
		n1 = strlen(str1);
		i = -1, j = -1;
		flag = 0;
		while(i < n1)
		{
			if (-1 == j || str1[i] == str2[j])
			{
				++i;
				++j;
			}
			else
			{
				j = Next[j];
			}
			if (j == n2)
			{
				count++;
				for (k = i - j; k < i; ++k)
				{
					str1[k] = 0;
				}
				flag = 1;
			}
		}
		for (i = 0, j = 0;i < n1; ++i)
		{
			if (str1[i])
			{
				str1[j++] = str1[i];
			}
		}
		str1[j] = 0;
	}
	return count;
}
int main()
{
	char str1[] = {"abccdde"};
	char str2[] = {"cd"};
	int num = Kmp(str1, str2);
	printf("num: %d, After Deleted: %s\n", num,str1);
	char str3[] = {"111111222"};
	char str4[] = {"12"};
	num = Kmp(str3, str4);
	printf("num: %d, After Deleted: %s\n", num,str3);
	char str5[] = {"1111133"};
	char str6[] = {"12"};
	num = Kmp(str5, str6);
	printf("num: %d, After Deleted: %s\n", num,str5);
	char str7[] = {"1111133"};
	char str8[] = {"1"};
	num = Kmp(str7, str8);
	printf("num: %d, After Deleted: %s\n", num,str7);
	char str9[] = {"12"};
	char str10[] = {"11112"};
	num = Kmp(str9, str10);
	printf("num: %d, After Deleted: %s\n", num,str9);
	char str11[] = {"12"};
	char str12[] = {"12"};
	num = Kmp(str11, str12);
	printf("num: %d, After Deleted: %s\n", num,str11);
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值