编程珠玑(二)寻找一个字符串中最长重复字串

例如字符串"banana"中最长重复字串为ana,这里用到了一个很简单的数据结构字符串数组,其实为一个字符串指针数组,一个char *类型的数组,用字符地址代表每个字符,可以节省空间。算法很简单,求出每个后缀数组,然后对后缀数组进行排序,最后求出相邻的两个数组之间的最大公共字串。

#include <iostream>
using namespace std;

void common_str(char *s, char **com);
void bubble(char **a, int s, int e);
int common_len(const char *s1, const char *s2); //求s1和s2从第一个字符开始相同的字符的个数

int main()
{
        char s[] = "banana";
        char *com = NULL;
        common_str(s, &com);
        printf("common str is %s\n", com);
        return 0;
}

void common_str(char *s, char **com)
{
        int len = strlen(s);
        char **a = new char *[len];
        int i = 0;
        while(s[i])
        {
                a[i] = &s[i];
                i++;
        }
        bubble(a, 0, len-1);

        int com_len = 0;
        char *com_str = NULL;
        for(int j=0; j<=len-2; j++)
        {
                int c_len = common_len(a[j], a[j+1]);
                if(c_len > com_len)
                {
                        com_len = c_len;
                        com_str = a[j];
                }
        }
        *com = new char[com_len + 1];
        memcpy(*com, com_str, com_len);
        (*com)[len] = '\0'; //这里这句话不写也可以,因为原来数组每个元素都为NULL,但是不可写成*com[len] = '\0';[]下标的优先级高于*
}

void bubble(char **a, int s, int e)
{
        int len = e-s+1;
        for(int i = len-1; i--; i>0)
                for(int j = 0; j<=i; j++)
                        if(strcmp(a[j], a[j+1]) > 0)
                        {
                                char *temp = a[j];
                                a[j] = a[j+1];
                                a[j+1] = temp;
                        }

}

int common_len(const char *s1, const char *s2)
{
        int len = 0;
        while(*s1 == *s2 && s1!=NULL && s2!=NULL)
        {
                len++;
                s1++;
                s2++;
        }
        return len;

}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值