码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-08-31 17:13:55      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

比如: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

技术分享

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

标签:

原文地址:http://www.cnblogs.com/audi-car/p/4773354.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!