读书人

面试题如何查找一个字符串里的最长连

发布时间: 2012-02-07 17:45:36 作者: rapoo

面试题,怎么查找一个字符串里的最长连续字符?
Find the longest run in a string
怎么查找一个字符串里的最长连续相同字符?
int longestrun(char* str)
{
// e.g. input ddbbbcxg, return 3 (because bbb has 3 b 's in a row)
// e.g. input hello, return 2 (because ll has 2 l 's in a row)
}

longestrun( "Gooooodbye ")); // should output 5
longestrun( "Interesting ")); // should output 1


[解决办法]
寒,不好意思,写的太快米认真...

int longestrun(char *str)
{
//~~~~~~~~~~~~~~~~~~~~
int i, cnt = 1, max = 0;
//~~~~~~~~~~~~~~~~~~~~

if (*str) {
max = 1;
for (i = 1; str[i]; i++) {
if (str[i] == str[i - 1]) {
cnt++;
} else {
if (cnt > max) {
max = cnt;
}

cnt = 1;
}
}
} else {
return 0;
}

if (cnt > max) {
max = cnt;
}

return max;
}
[解决办法]
程序好坏不能光看长短,效率和可读性是关键:

#include <stdio.h>

int longestrun(char* Str)
{
unsigned int uiMaxLen = 1;
unsigned int uiCurLen = 1;
if (Str)
{
char *pStr = Str + 1;
while (*pStr)
{
if (*(pStr - 1) == *pStr)
{
++uiCurLen;
}
else
{
uiMaxLen = (uiCurLen > uiMaxLen) ? uiCurLen : uiMaxLen;
uiCurLen = 1;
}
++pStr;
}
return (uiMaxLen > uiCurLen) ? uiMaxLen : uiCurLen;
}
return 0;
}
//测试程序,字符串长度不能超过1023
void main()
{
char pchStr[1024] = { '\0 '};
while (1)
{
scanf( "%s ",pchStr);
printf( "%d\n ", longestrun(pchStr));
}
}

读书人网 >C语言

热点推荐