实现用后缀数组求字符串的最长重复字串
2013-07-22 21:09
295 查看
原理在博文后缀数组的应用已经说明,下面是实现代码
/*
问题描述
给定一个字符串,求出其最长重复子串
例如:abcdabcd
最长重复子串是 abcd,最长重复子串可以重叠
例如:abcdabcda,这时最长重复子串是 abcda,中间的 a 是被重叠的。
*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdlib>
using namespace std;
int comlen(char *a, char *b)
{
int i=0;
while(*a && *a++==*b++) //返回a与b字符相同的长度
i++;
return i;
}
//用与回调函数
int pstrcmp(const void *a, const void *b)
{ return strcmp(*(const char* *)a, *(const char* *)b); }
int main(void)
{
int n=0, maxlen=0, maxi=0;
char a[1000],*pa[1000];
char ch;
while((ch=getchar())!='\n')
{
pa
=&a
;
a[n++]=ch;
}
a
='\0';
int i=0;
qsort(pa, n, sizeof(char*), pstrcmp); //得先排序后缀数组,不排序的话永远找不到
for(i=0; i<n-1; i++){
int temp=comlen(pa[i], pa[i+1]);
if(temp>maxlen) {
maxlen=temp;
maxi=i;
}
}
printf("the longest suffix is %s, and the length is %d\n", pa[maxi], maxlen);
return 0;
}
/*
问题描述
给定一个字符串,求出其最长重复子串
例如:abcdabcd
最长重复子串是 abcd,最长重复子串可以重叠
例如:abcdabcda,这时最长重复子串是 abcda,中间的 a 是被重叠的。
*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdlib>
using namespace std;
int comlen(char *a, char *b)
{
int i=0;
while(*a && *a++==*b++) //返回a与b字符相同的长度
i++;
return i;
}
//用与回调函数
int pstrcmp(const void *a, const void *b)
{ return strcmp(*(const char* *)a, *(const char* *)b); }
int main(void)
{
int n=0, maxlen=0, maxi=0;
char a[1000],*pa[1000];
char ch;
while((ch=getchar())!='\n')
{
pa
=&a
;
a[n++]=ch;
}
a
='\0';
int i=0;
qsort(pa, n, sizeof(char*), pstrcmp); //得先排序后缀数组,不排序的话永远找不到
for(i=0; i<n-1; i++){
int temp=comlen(pa[i], pa[i+1]);
if(temp>maxlen) {
maxlen=temp;
maxi=i;
}
}
printf("the longest suffix is %s, and the length is %d\n", pa[maxi], maxlen);
return 0;
}
相关文章推荐
- 字符串相关处理kmp,前缀数,后缀树,后缀数组,最长回文串,最长重复字串,最长非重复字串
- 字符串相关处理kmp,前缀数,后缀树,后缀数组,最长回文串,最长重复字串,最长非重复字串
- 通过后缀数组求字符串中最长重复字串
- 利用后缀数组求字符串的最长重复子串的算法 利用二维数组求两个字符串的最长公共字串(动态规划)
- 字符串相关处理kmp,前缀数,后缀树,后缀数组,最长回文串,最长重复字串,最长非重复字串
- 字符串相关处理kmp,前缀数,后缀树,后缀数组,最长回文串,最长重复字串,最长非重复字串
- 用后缀数组 求一个字符串的最长重复字串
- 查找一段文字中最长的重复字串 - 编程珠玑(排过序的后缀数组的应用)
- 【后缀数组 重叠重复字串个数大于k的最长长度】POJ - 3261 Milk Patterns
- 查找一段文字中最长的重复字串 - 编程珠玑(排过序的后缀数组的应用)
- 实用算法实现-第 8 篇 后缀树和后缀数组 [3 两个字符串的最长公共子串]
- 【编程珠玑】第十五章--字符串:用后缀数组查找最长不重叠的重复子串
- 转载:查找一段文字中最长的重复字串 - 编程珠玑(排过序的后缀数组的应用)
- POJ 2774 Long Long Message(后缀数组 两个字符串的最长公共字串 )
- poj 3450 Corporate Identity(后缀数组 多个字符串的最长公共字串)
- 实用算法实现-第 8 篇 后缀树和后缀数组 [3 两个字符串的最长公共子串]
- 利用后缀数组求字符串中的最长公共字串——编程珠玑15章
- poj 1743 字符串 后缀数组 不可重叠最长重复子串
- 【POJ】3693 Maximum repetition substring 【后缀数组——求最长连续重复字串】
- java实现list清除重复的字符串;arraylist动态数组;角谷定理最终得1,找出10000以内哪个数字的步骤最长