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; }
相关文章推荐
- Java字符串题目--删除给定字符串中出现次数最少的字符
- 在一个给定的字符串中删除指定的字符
- 华为机试 删除字符串中所有给定的子串
- 给定一个只包含小写字母的字符串,删除重复的字母,每个字母只出现一次。在所有结果中,输出字典顺序最小的。
- [删除字符串中多余的空格]给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个
- 给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢?
- 华为机试-删除字符串中所有给定的子串
- 给定字符串(ASCII码0-255)数组,请在不开辟额外空间的情况下删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。
- 华为机试 删除字符串中所有给定的子串
- 腾讯 2017 暑假实习生编程题(一):给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢? 输出需要删除的字符个数。
- 给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢? 输出需要删除的字符个数。
- 删除字符串中所有给定的子串
- 删除给定字符串中出现次数最多的字符
- 华为机试-删除字符串中所有给定的子串
- HDU 3336 Count the string(KMP+求给定字符串含前缀的数量)
- 删除字符串中多余的空格]给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个
- 编程实现删除字符串中所有给定的子串
- 删除给定字符串中的某一字符
- 给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢? 输出需要删除的字符个数。
- 删除字符串中所有给定的子串