bool checkZeroOnes(char* s) {
int count1=0;
int count0=0;
int max1=0;
int max0=0;
for(int x=0;x<strlen(s);x++)
{
if(count1!=0&&s[x]=='0')
{
if(count1>max1)
{
max1=count1;
}
count1=0;
}
if(count0!=0&&s[x]=='1')
{
if(count0>max0)
{
max0=count0;
}
count0=0;
}
if(s[x]=='1')
{
count1++;
}
if(s[x]=='0')
{
count0++;
}
}
if(max1>max0)
{
return true;
}
else
{
return false;
}
}
以上为笔者代码,其出错的主要原因为:如果最后的count1或者count0不为0且大于之前的最大值,将出现无法更新导致最后以0或1结尾的串的长度判断异常,导致错误
bool checkZeroOnes(char* s) {
int count1=0;
int count0=0;
int max1=0;
int max0=0;
for(int x=0;x<strlen(s);x++)
{
if(count1!=0&&s[x]=='0')
{
if(count1>max1)
{
max1=count1;
}
count1=0;
}
if(count0!=0&&s[x]=='1')
{
if(count0>max0)
{
max0=count0;
}
count0=0;
}
if(s[x]=='1')
{
count1++;
}
if(s[x]=='0')
{
count0++;
}
}
if(count1>max1)
{
max1=count1;
}
if(count0>max0)
{
max0=count0;
}
if(max1>max0)
{
return true;
}
else
{
return false;
}
}
以上为正确代码