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

寻找一个字符串中最长的公共子串

思路:

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[n]!='\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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值