编程珠玑(二)寻找一个字符串中最长重复字串
2012-07-24 16:34
302 查看
例如字符串"banana"中最长重复字串为ana,这里用到了一个很简单的数据结构字符串数组,其实为一个字符串指针数组,一个char *类型的数组,用字符地址代表每个字符,可以节省空间。算法很简单,求出每个后缀数组,然后对后缀数组进行排序,最后求出相邻的两个数组之间的最大公共字串。
#include <iostream> using namespace std; void common_str(char *s, char **com); void bubble(char **a, int s, int e); int common_len(const char *s1, const char *s2); //求s1和s2从第一个字符开始相同的字符的个数 int main() { char s[] = "banana"; char *com = NULL; common_str(s, &com); printf("common str is %s\n", com); return 0; } void common_str(char *s, char **com) { int len = strlen(s); char **a = new char *[len]; int i = 0; while(s[i]) { a[i] = &s[i]; i++; } bubble(a, 0, len-1); int com_len = 0; char *com_str = NULL; for(int j=0; j<=len-2; j++) { int c_len = common_len(a[j], a[j+1]); if(c_len > com_len) { com_len = c_len; com_str = a[j]; } } *com = new char[com_len + 1]; memcpy(*com, com_str, com_len); (*com)[len] = '\0'; //这里这句话不写也可以,因为原来数组每个元素都为NULL,但是不可写成*com[len] = '\0';[]下标的优先级高于* } void bubble(char **a, int s, int e) { int len = e-s+1; for(int i = len-1; i--; i>0) for(int j = 0; j<=i; j++) if(strcmp(a[j], a[j+1]) > 0) { char *temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } int common_len(const char *s1, const char *s2) { int len = 0; while(*s1 == *s2 && s1!=NULL && s2!=NULL) { len++; s1++; s2++; } return len; }
相关文章推荐
- 寻找一个字符串中的最长重复子串
- 求一个字符串的最长重复字串问题
- 返回一个字符串中重复出现的最长字串的长度及其开始字符
- 【每天学点算法题10.17】寻找一个字符串中的最长重复子串
- 寻找一个字符串中最长的重复子串
- 编程珠玑:用后缀数组寻找最长重复字符串
- 写一个函数,用来把一个字符串用指定的字符作为分隔符分割成若干个子串输出 | 写一个函数,用来返回一个字符串中重复出现的最长字串的长度及其开始地址
- 用后缀数组 求一个字符串的最长重复字串
- 面试题35:寻找一个字符串中最长的重复子串
- 【寻找一个字符串中最长的重复子串】
- 寻找一个字符串中最长的重复子串
- 在一个字符串中寻找到最长重复子串(1)
- 寻找一个字符串中的最长重复子串
- 寻找一个字符串中最长的重复子串,如 abcdabc 最长重复串 是abc
- 寻找一个字符串数组的最长公共前缀
- 求给定的某一个字符串中的最长的没有重复字符的子串的长度
- 求一个字符串中不带重复字母的最长substr的长度
- 寻找字符串的最长不重复子串,计算复杂度O(n),两种实现
- 定义一个栈的数据结构,实现min函数,要求push,pop,min时间复杂度是0(1);找出字符串中的最长子串,要求子串不含重复字符,时间复杂度是O(n);
- 字符串中的最长重复字串