输入字符串,求出其最长重复的子字符串

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

//字符串按字典序排序
int cmp(const void *a, const void *b)
{
	return strcmp(*(char **)a, *(char **)b);
}

/*返回两段字符串重复的长度*/
int cmpLen(char *s1,char *s2)
{
	int i = 0;
	while (s1[i]!='\0'&&s2[i]!='\0' && s1[i]==s2[i])
	{
		i++;
	}
	return i;
}

//获取后缀字符串数组
char **SuffixString(char *s)
{
	int len = strlen(s);
	char **ret = malloc(sizeof(char *)*len);   //保存后缀指针

	for (int i = 0; i < len; i++)
	{
		ret[i] = s + i;
	}
	return ret;
}

//返回最长重复子子串
char* maxIterateString(char *s)
{
	int len = strlen(s);
	char *ret = malloc(sizeof(char)*(len + 1));
	int maxLen = 0;
	char **suffixBuffer = SuffixString(s);
	qsort(suffixBuffer, len, sizeof(char *), cmp);  //对后缀字符串进行排序

	for (int i = 0; i < len - 1; i++)
	{
		int tempLen = 0;
		if ((tempLen =cmpLen(suffixBuffer[i], suffixBuffer[i + 1])) > maxLen)   //若重复子串更长则更新
		{
			maxLen = tempLen;
			memcpy(ret, suffixBuffer[i], sizeof(char)*maxLen);
		}
	}
	ret[maxLen] = '\0';
	free(suffixBuffer);
	return ret;
}

int main()
{
	char str[100] = "";
	gets(str);

	char *temp = maxIterateString(str);
	puts(temp);
	free(temp);
	system("pause");
	return 0;
}

参考:https://blog.csdn.net/renwotao2009/article/details/53039068

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值