統計字串中連續1和連續0的個數
/*
#include<stdio.h>
#include<iostream> //自己寫的
using namespace std;
void getmax(char*str)
{
int len = strlen(str);
int max0 = 0, max1 = 0;
int temp0 = 0, temp1 = 0;
int i;
for (i = 0; i < len; i++)
{
if (str[i] == '0')
{
temp0++;
if (str[i + 1] == '1')
{
if (temp0 > max0)
max0 = temp0;
temp0 = 0;
}
else
{
max0 = temp0;
}
}
if (str[i] == '1')
{
temp1++;
if (str[i + 1] == '0')
{
if (temp1 > max1)
max1 = temp1;
temp1 = 0;
}
else
{
max1 = temp1;
}
}
}
cout << "the number of '0' is : " << max0 << endl;
cout << "the namber of '1' is: " << max1 << endl;
}
int main()
{
char str[] = "101000000000011100000000000";
getmax(str);
getchar();
}
*/
#include<stdio.h>
#include<iostream>
void getmax(char *str, int *max0, int* max1) //把引數設定成指標才可以有多個輸出。
//
{
int i, len, tmp_max0 = 0, tmp_max1 = 0;
len = strlen(str);
for (i = 0; i < len; i++)
{
if (str[i] == '0')
{
if (str[i - 1] == '1')
{
if (tmp_max1 > *max1)
*max1 = tmp_max1;
tmp_max1 = 0;
}
tmp_max0++;
}
if (str[i] == '1')
{
if (str[i - 1] == '0')
{
if (tmp_max0 > *max0)
*max0 = tmp_max0;
tmp_max0 = 0;
}
tmp_max1++;
}
}
if (tmp_max1 > *max1)
*max1 = tmp_max1;
if (tmp_max0 > *max0)
*max0 = tmp_max0;
}
int main()
{
char str[] = "101000000000011100000000000";
int max0 = 0, max1 = 0;
getmax(str, &max0, &max1);
printf("\n%s\n", str);
printf("the number of consecutive character '0' are %d\n", max0);
printf("the number of consecutive character '1' are %d\n", max1);
getchar();
}