字符串常见问题总结(二)
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; }
相关文章推荐
- Sql常见问题总结二(Sql语句怎么样查询IP,游标去重复,各种函数使用,各种取时间格式,字符串精确排序,超时锁问题)
- C语言 字符串常见问题总结
- 字符串常见问题总结(一)
- Sql常见问题总结二(Sql语句怎么样查询IP,游标去重复,各种函数使用,各种取时间格式,字符串精确排序,超时锁问题)
- 常见字符串问题总结(三)
- IO模式设置网络编程常见问题总结—IO模式设置,阻塞与非阻塞的比较,recv参数对性能的影响—O_NONBLOCK(open使用)、IPC_NOWAIT(msgrcv)、MSG_DONTWAIT(re
- PHP函数之CURL: 常见问题总结
- LoadRunner常见问题总结
- 【面试】【Spring常见问题总结】【01】
- 字符串数组初始化相关问题总结
- svn常见问题,报错,命令及总结
- C#常见问题总结(三)
- Core+Data+常见问题的总结
- Php部分常见问题总结
- Android常见崩溃或闪退的问题描述及原因总结
- SQL SERVER中一些常见性能问题的总结
- 安卓开发中常见的问题总结
- 关于vtigercrm的常见问题总结
- Android常见问题总结(五)
- Vim常见指令与问题总结(五)---windowns下vim离线安装插件及介绍