zoukankan      html  css  js  c++  java
  • 统计一个01字符串中0,1连续出现的最大次数

    比如: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字符串的结束符飞‘’的下一个字符
    }
    
    static void delete_char(char *str,char c)    //删除字符串中指定的字符
    {
        if (str==NULL)
        {
            return ;
        }
        char *p=str;
        while(*p++)
        {
            if (*p!=c)
            {
                *str++=*p;
            }
        }
        *str='';
    }
    
    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;
    }
    image

    测试0101000000111111101003

    image

  • 相关阅读:
    sql日期操作
    用户活跃状态模型
    R基于Bayes理论实现中文人员特性的性别判定
    python的一点小常识
    [工作技能]SVN
    北大计算所词性标注集简表
    c++ boost 汉字和模式串混用的例子
    SVN文本文件报二进制属性的问题
    我的R代码备份
    FaceBook Twitter实习生简历求内推
  • 原文地址:https://www.cnblogs.com/audi-car/p/4773354.html
Copyright © 2011-2022 走看看