您的位置:首页 > 其它

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

2013-09-03 11:06 99 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐