在字符串中找出连续最长的数字串(C++ 坑)

来源:互联网 发布:python字符串转换字典 编辑:程序博客网 时间:2024/06/14 12:11

题目

输入

输入一个字符串。

输出

输出字符串中最长的数字字符串和它的长度。
如果数字字符串为空,则只输出0
如 input: dadfsaf output:0

样例输入

abcd12345ed125ss123058789

样例输出

123058789,9

思路

  1. 尽量循环一遍得到结果
  2. 通过标记判断连续的数字
  3. 一直寻找最大值
  4. 遇到相同的不必追加!!!

代码

#include <iostream>#include <string>using namespace std;int main(){    string str="",result="",subStr="";    getline(cin,str);    int counter=0,maxNum=0;    //统计最长字符串    for(string::iterator iter=str.begin(); iter!=str.end(); ++iter)    {        if(isdigit(*iter))        {            subStr+=(*iter);            counter++;            if(counter>maxNum)            {                result=subStr;                maxNum=counter;            }            else if(counter==maxNum)//此题AC,不需要把相同的输出,下面的评论就是坑啊!!!!!            {                //result+=subStr;            }        }        else        {            counter=0;            subStr="";        }    }    if(counter==0)    {        cout<<'0'<<endl;    }    else    {        cout<<result<<','<<maxNum<<endl;    }    return 0;}

这里写图片描述

#include <iostream>#include <cstdio>using namespace std;int Continuemax(char a[],char*&s){    int max=0,index,number=0;    for(int i=0; a[i]!='\0'; i++)    {        int flag=i;        while(a[flag] && a[flag]>='0' && a[flag]<='9')        {            number++;            flag++;        }        if(number>max)        {            max=number;            index=i;        }        number=0;    }    s=new char[max+1];    for(int i=0; i<max; i++)        s[i]=a[i+index];    s[max]='\0';    return max;}int main(){    char array[100];    char *s;    gets(array);    int length=Continuemax(array,s);    if (length==0)        cout<<'0'<<endl;    else    {        for(int i=0;i<length;i++)            cout<<s[i];        cout<<','<<length<<endl;    }}
0 0