您的位置:首页 > 其它

统计一个01字符串中0,1连续出现的最大次数

2015-08-31 16:22 519 查看
比如:0011000111

则表示0最大出现3次,1最大出现3次。

程序的思路很巧妙,不复杂。

// demo.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

static void strwe(char *str)
{
int len=0;
while(*str++)
len++;    //while循环结束以后  得到的就是字符串的实际长度
str-=2;        //while循环结束以后  str实际指向str字符串的结束符飞‘\0’的下一个字符
}

static void delete_char(char *str,char c)    //删除字符串中指定的字符
{
if (str==NULL)
{
return ;
}
char *p=str;
while(*p++)
{
if (*p!=c)
{
*str++=*p;
}
}
*str='\0';
}

static void caculate01(const char *str,int &max0,int &max1)
{
int temp0=0;
int temp1=0;
if (!str)
{
return ;
}
while(*str)
{
if (*str=='0')
{
max0+=1;
if (*(str+1)=='1')
{
if (max0>temp0)
{
temp0=max0;
}
max0=0;
}

}
else if (*str=='1')
{
max1+=1;
if (*(str+1)=='0')
{
if (max1>temp1)
{
temp1=max1;
}
max1=0;
}

}
str++;
}
max0=(max0>temp0)?max0:temp0;
max1=(max1>temp1)?max1:temp1;  //这里这样写的目的是防止01010001111样式的字符串  所带来的bug
//如果你不按照上两行这样写  你测试01010001111会得到  3  1  而不是   3   4
}

int main()
{
char str[]="01010001111";
int max0=0;
int max1=0;
caculate01(str,max0,max1);
cout<<"0连续出现的次数最多为:"<<max0<<endl;
cout<<"1连续出现的次数最多为:"<<max1<<endl;
return 0;
}






测试0101000000111111101003



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: