使用C语言,编写函数,找出找出0/1字符串中0和1连续出现的最大次数,如110000111111000111111111,0连续出现的最大次数是4,1连续出现的最大次数是9。
思路:定义两个临时变量,tmpmax0和tmpmax1,表示每次连续统计的个数;定义一个标识,表示当前统计的是0还是1,如果遇到0和1统计的转折点,记录转折前的连续统计最大个数,并将转折之前的临时值置0;值得注意的是:最后一段字符走不到转折点,需要在遍历完字符串之后比较并获取连续出现的最大统计值。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int get_max_count(char* szBuf, int* pMax0, int* pMax1)
{
if (szBuf == NULL || pMax0 == NULL || pMax1 == NULL)
{
return -1;
}
*pMax0 = 0;
*pMax1 = 0;
int nTmpCount0 = 0, nTmpCount1 = 0, nIndex = 0;
int nCurrNum = 0; //当前统计的字符值0或1
while (szBuf[nIndex] != '\0')
{
if (szBuf[nIndex] == '0')
{
if (nCurrNum == 1) //表示是统计1的转折点
{
if (*pMax1 < nTmpCount1)
{
*pMax1 = nTmpCount1;
}
nTmpCount1 = 0;
}
nCurrNum = 0;
++nTmpCount0;
}
else if (szBuf[nIndex] == '1')
{
if (nCurrNum == 0) //表示是统计0的转折点
{
if (*pMax0 < nTmpCount0)
{
*pMax0 = nTmpCount0;
}
nTmpCount0 = 0;
}
nCurrNum = 1;
++nTmpCount1;
}
++nIndex;
}
//最后一段字符串统计不会走到转折点统计逻辑,在此处统计
if (*pMax0 < nTmpCount0)
{
*pMax0 = nTmpCount0;
}
if (*pMax1 < nTmpCount1)
{
*pMax1 = nTmpCount1;
}
return 0;
}
int main()
{
char szBuf[32] = { 0 };
strcpy(szBuf, "110000111111000111111111");
int nMax0 = 0, nMax1 = 0;
get_max_count(szBuf, &nMax0, &nMax1);
printf("szBuf = [%s], max_0 = [%d], max_1 = [%d]\n", szBuf, nMax0, nMax1);
return 0;
}
|