求一个字符串中连续出现的次数最多的子串[C语言实现]

来源:互联网 发布:学而后知不足事例 编辑:程序博客网 时间:2024/06/08 05:21
#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAX_SIZE 50int find_con_sub(char *str, char **ret);int main(){        char str[] = "aabcdabcdabcdef";        char *ret = NULL;        int time = con_sub(str, &ret);if (time != 1){printf("%s occurrs %d times in %s!\n", ret, time, str);}else{printf("%s don't have continus sub str!\n", str);}free(ret);ret = NULL;        return 0;}int con_sub(char *str, char **ret){        int max_time = 0;//连续出现的最多次数        int ret_len = 0;//连续出现的字符串的长度        char *addr = NULL;//连续出现字符串的起始地址int i,j,k;int temp_time = 0;        int len = strlen(str);        char *a[MAX_SIZE];//= (char **)malloc(sizeof(char *)*len);指针数组用于存储后缀数组        //生成后缀数组        for(i=0; i<len; i++)                a[i] = &str[i];        //重复字符串的长度范围为1到(len+1)/2        for(i=1; i<=(len+1)/2; i++)        {                //当重复的字符串长度为i的时候,如果是连续出现的,那么第j和第j+i个后缀数组前面为重复的字符串                for(j=0; j+i<=len-1; j+=1)                {                        k = j;                        temp_time = 1;                        while(k+i <= len-1 && strncmp(a[k], a[k+i], i) == 0)                        {                                temp_time++;                                k += i;                        }                        if(temp_time > max_time)                        {                                max_time = temp_time;                                ret_len = i;                                addr = a[k];                        }                }        }*ret = (char*) malloc(sizeof(char) * (ret_len+1));strncpy(*ret, addr, ret_len);(*ret)[ret_len] = '\0';        return max_time;}