您的位置:首页 > 其它

字符串常见问题总结(二)

2013-11-15 20:35 344 查看
寻找一个字符串中最长的公共子串

思路:
1.求出该字符串的所有后缀子串
2.对这些后缀子串进行排序
3.比较相邻的后缀子串,求出它们最大的公共子串的长度

/*
实现如何求取字符串的所有后缀子串。
可以定义一个指针数组,使每个指针分别指向字符串
不同的位置。实现代码如下。
*/
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
char str[100];
char *plast[100];
int n=0;
/*
实现如何求取字符串的所有后缀子串。可以定义一个指针数组,使每个指针分别指向字符串不同的位置。实现代码如下。
*/
void cal_plast(char *str)
{
while(str
!='\0')// 可以用strlen代替
n++;
for(int j =0; j<n; j++)
plast[j] = &str[j]; //将字符串每个元素的地址分别赋给指针数组
}
/*实现后缀数组的排序;可以利用<cstdlib>库中的void qsort(void *base, int ele_num, int ele_size, int(*fcmp)(const void*, const void*))实现对后缀子串数组的排序,即:qsort(plast,n,sizeof(char*),fcmp);fcmp的定义如下*/
int fcmp(const void* p1, const void* p2)
{
return strcmp(*(char* *)p1, *(char* *)p2);//必须要这样写,否则在排序的时候会得不到想要的结果,但是不知道为什么,求高人指点。
}
int comlen( char *p, char *q )
{
int i = 0;

while( *p && (*p++ == *q++))
{
++i;
}

return i;
}

int  find(const char * str)
{
cal_plast((char*)str);
for(int j =0; j < n; j++)
cout<<plast[j]<<endl;
qsort(plast,n,sizeof(char*),fcmp);
for(int j =0; j < n; j++)
cout<<plast[j]<<endl;
int i;
int max=0;
int index = 0;
for(i=0; i<n-1; i++)
{
int num = comlen(plast[i], plast[i+1]);
if(num > max)
{
max = num;
index = i;
}
}
for(int j =0; j<max; j++)
cout<<plast[index][j];//尤其要注意这里。也可以写成*(plast //+index)[j]
return 0;
}
int main()
{
gets(str);
find(str);
return 0;
}


上面提到了快速排序算法,下面就实现一个简单的递归排序算法,voidmyqsort(int * p, int low, int high)。

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

void swap(int &a, int &b)
{
a ^=b;
b^=a;
a^=b;
}
void myqsort(int *p, int low, int high)
{
if(low > high||low<0||high <0)
{
cout<<"parameter error"<<endl;
return;
}
if(low == high)
return;
int pivot = p[low];
int i = low+1, j = high;
while(i < j)
{
while(pivot < p[j]&&i<j)
j--;
while(pivot > p[i]&&i<j)
i++;
if(i < j)
swap(p[i],p[j]);
}
if(p[j] < pivot)// 这里是大于或者小于是有上面的 两个while循环的次序决定的
swap(p[low], p[j]);
if(j > low+1)
myqsort(p, low, j-1);
if(j+1 < high)
myqsort(p, j+1, high);
}
int main()
{
int arr[] = {5,4,6,9,8,7,3,2,1};
myqsort(arr, 0,8 );
for(int i =0; i<9; i++)
cout<<arr[i]<<"  ";
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: