求已知串中最长空格序列的长度,要求尽量少检查串的字符。提示:空格序列长度增大,程序将变得更快。
#include"stdio.h"
#define N 1000
void main()
{
int i = 0;
char a[N];
char tempchar;
int spaceCount = 0;
int spaceCountOld = 0;
int tempint = 0;
int cycleCount = 0;
memset(a,0, N * sizeof(char));
for (i = 0; i < N; ++i)
{
if ((tempchar = getchar()) == EOF) break;
a[i] = tempchar;
}
printf("\ndatasize = %d\n",i);
i = 0;
while (i < N && a[i] != 0)
{
++ cycleCount;
if(a[i] != ' ')
{
tempint = spaceCount == 0 ? 1 : spaceCount;
if (a[i + tempint] != ' ') i += tempint;
else ++ i;
if (spaceCount > spaceCountOld)
{
spaceCountOld = spaceCount;
}
spaceCount = 0;
}
else {++ spaceCount; ++ i;}
}
if (spaceCount > spaceCountOld)
{
spaceCountOld = spaceCount;
}
printf("\nspaceCountOld = %d\n", spaceCountOld);
printf("\cycleCount = %d\n", cycleCount);
}