//编写一个 C 函数,该函数在一个字符串中找到可能的最长的子字符串,且该字符串是由同一字符组成的。
//假如有相同大小长度的子字符串 怎么输出两个呢?
//用两个函数,一个记录最大的子字符串 一个输出字符串
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void print(char ch,int count){
int i;
for(i = 0; i < count;i++){
printf("%c",ch);
}
printf("%c\n",ch);
}
int * sort(char * ch,int * count) {
//边排序边调整
}
void traverse(char * ch,int * count,int CountLen){
//递归输出最大长度子字符串 可能有相同长度的大小的字符串
//本功能未实现判断是否有重复的子字符串 感觉也没比要,
//如果有重复的子字符串也符合题意,可以个人自我发挥吧
int count_temp;
int first = count[CountLen],second = count[CountLen-1];//最大值,次大值
while(CountLen--){
count_temp = count[CountLen-1];
if(first > count_temp){
print(first,ch[CountLen]);
break;
}
if(first == count_temp){
print(first,ch[CountLen]);
print(second,ch[CountLen-1]);
}
}
}
void search(char *source,char * ch,int * count){
char *cpTemp = NULL,*cpDest = NULL,*cpTemp2 = NULL;
int iCount = 0,i = 0; //用来计数
while(*source){
cpTemp = source;
cpTemp2 = source;
while(cpTemp2 == cpTemp){ //char ----int 对应
++iCount;
++cpTemp;
}
count[i] = iCount;//i = 0
ch[i++] = *cpTemp;
if(!*source)
break;
++source;
}
//重新对count数组排序,然后对对应的char[]数组用temp变量保存缓存调整位置和count对应
sort(ch,count);
//这样一来如上已经存储了某个字符和对应的连续长度 且是有序的
//将int[]数组从后端开始找出最大count和次大count 相等输出两个 继续往前判断 相等继续输出
// 直到两个count值不相等
traverse(ch,count,i);
}
int main(){
//char * str = NULL;
char *source1 = "aaccbjgggggg"; //gggggg
char *source2 = "aabbcccddd"; //ccc ddd
char ch[] ={'\0'} ;//单个的字符数组字符
int count[] = {0}; //计数数组
printf("Source1 :\n");
search(source1,ch,count);
printf("Source2:\n");
search(source2,ch,count);
source1 = NULL;
source2 = NULL;
return 0;
} 最长同一字符组成的子字符串
最新推荐文章于 2022-03-17 09:12:48 发布
本文介绍了一个C语言函数,该函数用于在一个给定的字符串中查找由单一字符组成的最长子字符串。文章提供了完整的源代码,并通过两个示例演示了如何使用此函数。
907

被折叠的 条评论
为什么被折叠?



