查找字符串中字符间不同的最大子串

查找不同字符最大子串
本文介绍了一个C语言实现的算法,用于查找给定字符串中包含不同字符的最大子串,并返回该子串及其长度。通过记录每个字符最后出现的位置来高效地解决此问题。

 

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

#define SetSize 256 //字符集大小

//说明:查找字符串中字符间不同的最大子串
//参数:string 待搜索字符串
// rst 存放找到的最大子串
//返回:找到最大子串长度
int findMaxSubstring(const char *string, char *rst){

const char *p = string;
const char *substring = p; //当前子串
int length = 0; //当前子串长度
const char *maxSubstring = substring; //已经找到的最大子串
int maxLength = 0; //已经找到的最大子串长度

// 遍历字符串过程中,字符最后一次出现的位置
const char* position[SetSize];
memset(position,
0, SetSize * sizeof(char *));

char ch; //
while ((ch = *p) != '\0')
{
if (position[ch] < substring){ //字符在当前子串首次出现
length++;
if (length > maxLength){
maxSubstring
= substring;
maxLength
= length;
}
}
else {
substring
= position[ch] + 1; //当前子串从该字符上次出现的位置后面开始
length = p - position[ch];
}

position[ch]
= p; // 保存字符的位置
p++;
}

// 拷贝找到的最大子串
strncpy(rst, maxSubstring, maxLength);
rst[maxLength]
= '\0';
return maxLength;
}


 

 

 

转载于:https://www.cnblogs.com/custa/archive/2010/08/29/1812032.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值