题目链接
题目描述
读入一个字符串str,输出字符串str中的连续最长的数字串

#include<iostream>
#include<algorithm>
#include<cstring> 
using namespace std;
const int maxn = 1e6+5;
int main()
{
    char str[maxn];
    gets(str);
    int len=strlen(str);
    int maxv=0;                //用来保存最长数字串的长度 
    int max_pose=0;            //用来保存最长数字串的起始位置 
    for(int i=0;i<len;i++)    //遍历这个字符串 
    {
        if(str[i]-'0'>=0 && str[i]-'0'<=9)    //如果是数字的话 
        {
            int j=i;
            int ans=0;                        //当前数字串长度 
            while(str[j]-'0'>=0 && str[j]-'0'<=9 && j<len)    //如果当前位置是数字,并且位置合法 
            {
                ans++;                                         
                j++;
            }
            if(ans>maxv)                     //如果当前数字串比之前的长,则更新长度和位置 
            {
                maxv=ans;
                max_pose=i;    
            }
            i=j+1;                             //下次从这个数字串的末尾遍历就可以了 
        }
        
    }
    for(int i=max_pose;i<max_pose+maxv;i++)    //输出答案 
    {
        cout<<str[i];
    }
    cout<<endl;
    return 0;
}
Last modification:September 21st, 2019 at 12:11 am
如果觉得我的文章对你有用,请随意赞赏