最长重复子串

方法一:

#include<iostream>
#include<cstring>
using namespace std;

char data[100];//全局变量,用于保存最长重复子串

void GetSub(char* str);

int main()
{
	char *str = "abcdbcdbcb";
	GetSub(str);
	char* p = data;
	cout<<data<<endl;
	while(*p != '\0')
		cout<<*p++;
	cout<<endl;
	
}

void GetSub(char* str)
{
char *p,*q,*temp;
p = str;
q = p + 1;
int len = 0;//记录连续重复子串的长度
int max = 0;//记录连续重复子串的最大长度

 int i=0;

while(*p != '\0')
{
temp = p;
while(*q != '\0')
{
if(*q != *p)
    q++;
else
{
len++;//长度自加
p++;//指针后移
q++;
}
}
if(len > max)
{
      	i = 0;
	max = len;
	len = 0;
	while(temp != p)
{
data[i] = *temp;
temp++;
i++;
}
}
p++;
q = p + 1;
}
data[i] = '\0';//字符数组的最后一个元素需要设置为'\0'
}


方法二:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXCHAR 5000 //最长处理5000个字符

char c[MAXCHAR], *a[MAXCHAR];

int comlen( char *p, char *q ){
    int i = 0;
    while( *p && (*p++ == *q++) )
        ++i;
    return i;
}

int pstrcmp( const void *p1, const void *p2 ){
    return strcmp( *(char* const *)p1, *(char* const*)p2 );
}

int main(  ){
    char ch;
    int  n=0;
    int  i, temp;
    int  maxlen=0, maxi=0;
    printf("Please input your string:\n");
    while( (ch=getchar())!='\n' ){
        a[n]=&c[n];
        c[n++]=ch;
    }
    c[n]='\0';
    qsort( a, n, sizeof(char*), pstrcmp );
    for(i=0; i<n-1; ++i ){
        temp=comlen( a[i], a[i+1] );
        if( temp>maxlen ){
            maxlen=temp;
            maxi=i;
        }
    }
    printf("%.*s\n",maxlen, a[maxi]);
    system("PAUSE");
    return 0;
}


你可能感兴趣的:(最长重复子串)