今天在一个网页上看到一个C/C++面试题 ,要求在一个给定的字符串中查找连续重复且长度最大的第一个子串。
例如:abcbcfkhhhhabab,返回应该是bc,要求效率最优
想了很久,虽然实现了,但是效率不怎么满意,大家如果有更好的算法,请回帖哈。。
我的算法如下:
enum FindStatus
{
VALID = 0, //返回合法结果
NULLSTR = 1, //目标字符串为空
VALID_LEN = 2, // 目标字符串长度不够
NO_SERIERS=3 //目标字符串没有连续重复数据
};
FindStatus FindSeriesString(char *pSource,char *pResult)
{
if(NULL==pSource)
{
return NULLSTR;
}
if(strlen(pSource)<=1)
{
return VALID_LEN;
}
char * p = pSource;
char * q = NULL;
char * pIndex = NULL;
int maxlen = 0;
while((*p)!='/0')
{
q = p+1;
while((*q)!='/0')
{
if(*q==*p)
{
if(q==p+1)
{
if(maxlen<1)
{
maxlen = 1;
pIndex= p;
}
}
else
{
int i=0;
for(i=1; i<q-p; i++)
{
if(*(p+i)!=*(q+i))
{
break;
}
}
if(i==q-p)
{
if(maxlen<q-p)
{
maxlen = q-p;
pIndex = p;
}
}
}
}
q++;
}
p++;
}
if(maxlen>=1)
{
strncpy(pResult,pIndex,maxlen);
return VALID;
}
else
{
return NO_SERIERS;
}
}
例如:abcbcfkhhhhabab,返回应该是bc,要求效率最优
想了很久,虽然实现了,但是效率不怎么满意,大家如果有更好的算法,请回帖哈。。
我的算法如下:
enum FindStatus
{
VALID = 0, //返回合法结果
NULLSTR = 1, //目标字符串为空
VALID_LEN = 2, // 目标字符串长度不够
NO_SERIERS=3 //目标字符串没有连续重复数据
};
FindStatus FindSeriesString(char *pSource,char *pResult)
{
if(NULL==pSource)
{
return NULLSTR;
}
if(strlen(pSource)<=1)
{
return VALID_LEN;
}
char * p = pSource;
char * q = NULL;
char * pIndex = NULL;
int maxlen = 0;
while((*p)!='/0')
{
q = p+1;
while((*q)!='/0')
{
if(*q==*p)
{
if(q==p+1)
{
if(maxlen<1)
{
maxlen = 1;
pIndex= p;
}
}
else
{
int i=0;
for(i=1; i<q-p; i++)
{
if(*(p+i)!=*(q+i))
{
break;
}
}
if(i==q-p)
{
if(maxlen<q-p)
{
maxlen = q-p;
pIndex = p;
}
}
}
}
q++;
}
p++;
}
if(maxlen>=1)
{
strncpy(pResult,pIndex,maxlen);
return VALID;
}
else
{
return NO_SERIERS;
}
}